<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oleg Litvinov on Medium]]></title>
        <description><![CDATA[Stories by Oleg Litvinov on Medium]]></description>
        <link>https://medium.com/@olegolego1997?source=rss-ebd0f4cac821------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LD-EpwLqX88jXp9g.jpg</url>
            <title>Stories by Oleg Litvinov on Medium</title>
            <link>https://medium.com/@olegolego1997?source=rss-ebd0f4cac821------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:43:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olegolego1997/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Text anonymization with Presidio and Faker]]></title>
            <link>https://medium.com/@olegolego1997/text-anonymization-with-presidio-and-faker-be251f36d5bf?source=rss-ebd0f4cac821------2</link>
            <guid isPermaLink="false">https://medium.com/p/be251f36d5bf</guid>
            <category><![CDATA[anonymization]]></category>
            <category><![CDATA[fake-data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-safety]]></category>
            <category><![CDATA[presidio]]></category>
            <dc:creator><![CDATA[Oleg Litvinov]]></dc:creator>
            <pubDate>Mon, 13 Sep 2021 05:41:12 GMT</pubDate>
            <atom:updated>2021-09-13T05:41:12.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QR5KmODEOlorJ-nv" /><figcaption>Photo by <a href="https://unsplash.com/@matthewhenry?utm_source=medium&amp;utm_medium=referral">Matthew Henry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>On one of my projects I faced the problem of dealing with Personal Identifiable Information (PII). To share our data with third-parties we decided to add an anonymization step to the preprocessing. In this article I will describe an example of data anonymization using two awesome libraries: <a href="https://github.com/microsoft/presidio">Presidio</a> and <a href="https://github.com/joke2k/faker">Faker</a>.</p><p>Agenda:</p><ol><li>Presidio analyzer for finding sensitive data</li><li>Presidio anonymizer</li><li>Faker for generating diverse synthetic entities</li><li>final pipeline for text anonymisation</li></ol><p>The desired result will look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*NLCn82Ro9HjxQz2D1WHTgQ.png" /></figure><p>The link to the full notebook with examples will be shared in the end of the article.</p><h3>Analyzer</h3><p>At first, we need to install the library:</p><pre>!pip install presidio-analyzer</pre><p>Below you will find a brief diagram of how it works. Generally, it uses NER, regex, and rules for detecting personal information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pQt0gr3FkKK8_QfJ.png" /><figcaption>Presidio Analyzer diagram from the <a href="https://microsoft.github.io/presidio/analyzer/">documentation</a></figcaption></figure><p>Presidio supports both SpaCy and Stanza as its internal NLP engine for finding named entities. The details may be found <a href="https://microsoft.github.io/presidio/analyzer/customizing_nlp_models/">here</a>. I prefer SpaCy and that’s why I will download their model.</p><pre>!python -m spacy download en_core_web_md</pre><p>Then we need to expricitly select this model because by default the analyser uses spacy en_core_web_lg for English language</p><pre># Create configuration containing engine name and models<br>configuration = {<br>    &quot;nlp_engine_name&quot;: &quot;spacy&quot;,<br>    &quot;models&quot;: [{&quot;lang_code&quot;: &quot;en&quot;, &quot;model_name&quot;: &quot;en_core_web_md&quot;}],<br>}</pre><p>Having the configuration, we can create the analyzer</p><pre>from presidio_analyzer import AnalyzerEngine<br>from presidio_analyzer.nlp_engine import NlpEngineProvider</pre><pre># Create NLP engine based on configuration<br>provider = NlpEngineProvider(nlp_configuration=configuration)<br>nlp_engine = provider.create_engine()</pre><pre># the languages are needed to load country-specific recognizers <br># for finding phones, passport numbers, etc.<br>analyzer = AnalyzerEngine(nlp_engine=nlp_engine,<br>                          supported_languages=[&quot;en&quot;])</pre><p>Let us analyze one example</p><pre>example_text = &quot;Hi. My name is Oleg. I was born in Saint-Petersburg, Russia in 1997. Some random phone number: 51-855-831-2384. Yesterday I ate soup. Send something there helpline@lgbt.foundation. IBAN example AT483200000012345864&quot;</pre><pre># language is a required parameter. So if you don&#39;t know <br># the language of each particular text, use language detector<br>results = analyzer.analyze(text=example_text,<br>                           language=&#39;en&#39;)</pre><pre>for res in results:<br>    print(res)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*AhbBVxkhC97_ZlLrdBWd7w.png" /></figure><p>Here we see entities, their start and end indices, and kind of a confidence score. If you want to analyse only a limited set of entities, pass a list with their names to a corresponding parameter of the analyze function.</p><p>And here is the same text with entities marked and coloured with a random non-black colour</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*gpGxca9mfrxVVqPTa7ZGtw.png" /></figure><p>We see that there is a collision at the end as a domain is a part of an email address.</p><p>From the <a href="https://microsoft.github.io/presidio/anonymizer/">documentation</a>:</p><blockquote>As the input text could potentially have overlapping PII entities, there are different anonymization scenarios:</blockquote><blockquote>• No overlap (single PII) — single PII over text entity, uses a given or default anonymizer to anonymize and replace the PII text entity. <br>•Full overlap of PIIs — When one text have several PIIs, the PII with the higher score will be taken. Between PIIs with identical scores, the selection will be arbitrary. <br>• One PII is contained in another — anonymizer will use the PII with larger text. <br>• Partial intersection — both will be returned concatenated.</blockquote><p>Also, not all entities are captured well: the phone number is cut. For this purpose <a href="https://microsoft.github.io/presidio/analyzer/adding_recognizers/">custom recognisers</a> are made. They may be used for your particular patterns. These may be used, for examle, for finding urls, non-common symbol sequences, specific phrases.</p><p>Finally, a decision for each entity may be explained. Details on the <a href="https://microsoft.github.io/presidio/analyzer/decision_process/">decision process</a>.</p><h3>Anonymizer</h3><p><a href="https://microsoft.github.io/presidio/anonymizer/">Anonymizer</a> is the second pillar of the presidio library.</p><p>Again, the library:</p><pre>!pip install presidio-anonymizer</pre><p>From the diagram below we see that on the input side the anonymizer expects the original text and the detected PII from the analyzer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KDfF5OOosZBwjtJx.png" /><figcaption>Presidio Anonymizer diagram from the <a href="https://microsoft.github.io/presidio/anonymizer/">documentation</a></figcaption></figure><p>As analyzer, anonymizer also has an Engine. Let us launch it!</p><pre>from presidio_anonymizer import AnonymizerEngine</pre><pre>anonymizer = AnonymizerEngine()</pre><pre>anonymized_text = anonymizer.anonymize(text=example_text, analyzer_results=results).text</pre><pre>print(anonymized_text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*oS5olwyvcXZDuMqOYfH9Rw.png" /></figure><p>We can see that by default the entities are replaced with their entity name. Quite well. But can we make it more flexible? Of course! presidio has <a href="https://microsoft.github.io/presidio/anonymizer/">operators</a> for this.</p><pre>from presidio_anonymizer.entities.engine import OperatorConfig</pre><pre>operators={&quot;PERSON&quot;: OperatorConfig(operator_name=&quot;replace&quot;, <br>                                    params={&quot;new_value&quot;: &quot;REPLACED_NAME&quot;}),<br>           &quot;LOCATION&quot;: OperatorConfig(operator_name=&quot;mask&quot;, <br>                                      params={&#39;chars_to_mask&#39;: 10, <br>                                              &#39;masking_char&#39;: &#39;*&#39;,<br>                                              &#39;from_end&#39;: True}),<br>           &quot;DEFAULT&quot;: OperatorConfig(operator_name=&quot;redact&quot;)}</pre><pre>anonymized_text = anonymizer.anonymize(text=example_text, <br>                                       analyzer_results=results,<br>                                       operators=operators).text</pre><pre>print(anonymized_text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*EzssIrm9fedc70NWt0hj_g.png" /></figure><p>We have <em>masked </em>locations, <em>replaced </em>persons with a pre-defined value, and removed (<em>redact</em> parameter value) all other entities found. In addition to that, you may use <em>hash</em>, <em>encrypt</em>, and <em>custom </em>operator names. The latter is the most valuable, from my perspective. With custom operator we can, for examle, apply custom (surprisingly) logic to the original entity, select randomly from a set of pre-defined values, or even generate a new anonymized value from scratch!</p><pre>operators={&quot;PERSON&quot;: OperatorConfig(operator_name=&quot;custom&quot;, <br>                                    params={&quot;lambda&quot;: lambda x: random.choice([&#39;Neo&#39;, &#39;Paul&#39;])}),<br>           &quot;DEFAULT&quot;: OperatorConfig(operator_name=&quot;custom&quot;, params={&quot;lambda&quot;: lambda x: x[::-1]})}</pre><pre>anonymized_text = anonymizer.anonymize(text=example_text, <br>                                       analyzer_results=results,<br>                                       operators=operators).text</pre><pre>print(anonymized_text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*u_LMkSgE0YcS2980YW5iNQ.png" /></figure><p>If you launch the cell for several times, you may notice that sometimes PERSON entities will be replaced with Neo and sometimes with Paul. Other entities will be reversed.</p><p>Let us add more power to the anonymization part!</p><h3>Faker</h3><p>Last but not least component of the pipeline is <a href="https://github.com/joke2k/faker">Faker</a> — library for generating fake data. As always:</p><pre>!pip install Faker</pre><p>Here is a basic example from the library:</p><pre>from faker import Faker</pre><pre>fake = Faker()</pre><pre>print(&#39;random name:&#39;, fake.name())<br>print(&#39;random address:&#39;, fake.address())<br>print(&#39;random phone number:&#39;, fake.phone_number())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*YTx8Kr-3kGIwubUOCGX8-w.png" /></figure><p>Generally, faker operates with large collections of local names, surnames, prefixes, etc. But simple interface and variety do their best to use this library instead of your own-defined values. Interestingly, we may limit the locales from which we generate our entities.</p><pre>fake = Faker(locale=[&#39;jp_JP&#39;])</pre><pre>for i in range(5):<br>    print(fake.name())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*6h46N5x2lU-p6b6v4D1zng.png" /></figure><pre>fake = Faker(locale=[&#39;en_US&#39;, &#39;en_GB&#39;, &#39;en_CA&#39;, &#39;fr_FR&#39;])</pre><pre>for i in range(10):<br>    print(fake.name())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*-b8ZD2ZM5zhqBUBIioz2IA.png" /></figure><p>To use faker during the anonymization step, we need to create operators with lambda functions.</p><pre>fake_operators = {<br>    &quot;PERSON&quot;: OperatorConfig(&quot;custom&quot;, {&quot;lambda&quot;: lambda x: fake.name()}),<br>    &quot;PHONE_NUMBER&quot;: OperatorConfig(&quot;custom&quot;, {&quot;lambda&quot;: lambda x: fake.phone_number()}),<br>    &quot;EMAIL_ADDRESS&quot;: OperatorConfig(&quot;custom&quot;, {&quot;lambda&quot;: lambda x: fake.email()}),<br>    &quot;LOCATION&quot;: OperatorConfig(&quot;replace&quot;, {&quot;new_value&quot;: &quot;USA&quot;}),<br>    &quot;DEFAULT&quot;: OperatorConfig(operator_name=&quot;mask&quot;, <br>                              params={&#39;chars_to_mask&#39;: 10, <br>                                      &#39;masking_char&#39;: &#39;*&#39;,<br>                                      &#39;from_end&#39;: False}),<br>}</pre><pre>anonymized_text = anonymizer.anonymize(text=example_text,<br>                                       analyzer_results=results,<br>                                       operators=fake_operators<br>                                       ).text<br>print(anonymized_text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*4UX_M7sWYMf3i_aX6GqbTA.png" /></figure><p>And that’s it! The tool works quite well out of the box and may be finalised using custom custom <a href="https://microsoft.github.io/presidio/analyzer/adding_recognizers/">recognisers</a> and via analysing the <a href="https://microsoft.github.io/presidio/analyzer/decision_process/">decision process</a>.</p><p>Full notebook may be found <a href="https://github.com/OlegBEZb/text_anonymization">here</a>.</p><h3>Conclusion</h3><p>In this article I have briefly described a python pipeline for text anonymization. The pipeline suggested may be easily adjusted for your personal needs with more heavy NER models (en_core_web_trf, for example), custom rules, another confidence scores, etc. Moreover, you can upgrade your <a href="https://microsoft.github.io/presidio/analyzer/languages/">pipeline for multiple languages</a>.</p><p>From the productionalization point of view, the code may also be launched with Spark via simply adding several lines of code (check the full code). Or you can <a href="https://microsoft.github.io/presidio/samples/docker/">use Presidio as an HTTP service</a>.</p><p>Moreover, <a href="https://microsoft.github.io/presidio/image-redactor/">Presidio works with images</a>.</p><h3>PS</h3><p>I really hope you enjoyed the article and found it usefull for you and your needs. Any comments and suggestions are welcome!)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be251f36d5bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>