MichaelWelsch
commited on
Update README.md
Browse files
README.md
CHANGED
@@ -1,3 +1,382 @@
|
|
1 |
-
---
|
2 |
-
license: apache-2.0
|
3 |
-
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: apache-2.0
|
3 |
+
---
|
4 |
+
# The GDPR Input Detection and Anonymization model
|
5 |
+
|
6 |
+
The **The GDPR Input Detection and Anonymization model** is designed to protect sensitive information locally before it is processed by larger AI models in external clouds.
|
7 |
+
|
8 |
+
External cloud suppliers store every input for at least 30 days!
|
9 |
+
|
10 |
+
Inference costs of small or big model differ by factor 100!
|
11 |
+
|
12 |
+
You can't give LLM access to employees without caring about GDPR and company compliance.
|
13 |
+
|
14 |
+
|
15 |
+
## Intended Use
|
16 |
+
|
17 |
+
The model is made to bridge the user inputs to external LLM input like a firewall or proxy
|
18 |
+
|
19 |
+
The model analysis the user prompts and computes two scores.
|
20 |
+
|
21 |
+
The first score helps to identify if it needs a small or more cabable model to process the user input. The second score rates the sensitivity of the prompt. When it detects sensitive information, the further cloud processing of the prompt can be blocked or at least be replaced by an anonymized version.
|
22 |
+
|
23 |
+
|
24 |
+
## Complexity Scoring
|
25 |
+
|
26 |
+
The score rates the complexity of a task on a scale from 1 to 10, where **1 represents simple information retrieval of world knowledge** and **10 involves highly complex, expert-level analysis of domain specific content**. With lower scores, smaller models like **LLaMA** are sufficient, while mid to high scores suggest using more powerful models like from OpenAI or Anthropic.
|
27 |
+
|
28 |
+
Also the score incresease, if the number of instructions and contraints in a prompt increase.
|
29 |
+
|
30 |
+
This scoring system provides guidance for selecting the right model, helping to **save costs** and **optimize resources** by aligning the task’s complexity with the appropriate computational power.
|
31 |
+
|
32 |
+
|
33 |
+
| **Score** | **Description** | **Example Tasks** | Number of Instructions and Constraints* | **Suggested Models** |
|
34 |
+
|:---------:|--------------------------------------------|-------------------------------------------------------------------|-|------------------------------------|
|
35 |
+
| **1** | Basic fact retrieval or identification | "What is the capital of France?" | 1 | Llama, smaller models |
|
36 |
+
| **2** | Simple rephrasing or minor adjustments | "Paraphrase the sentence: 'The dog barked loudly.'" | 1 | Llama, GPT-4o Mini |
|
37 |
+
| **3** | Summaries or brief overviews | "Summarize the key points of a short text." | 1 | Llama, GPT-4o Mini |
|
38 |
+
| **4** | List creation or short reasoning | "List three reasons why the following exercise is more beneficial in Greek than in Italy: Here is the exercise: ..." | 2 | GPT-4o Mini |
|
39 |
+
| **5** | Key point extraction, organized info | "Exctract challenges and solutions as bullet points. no summary, no intro. Here is the text: ..." | 2 | GPT-4o Mini |
|
40 |
+
| **6** | Basic narrative or simple analysis | "Write a short story about a character learning a lesson. Written in Harry Potter style, but not about Harry potter, but for coding amateur, humorous" | 3 | GPT-4o Mini |
|
41 |
+
| **7** | Multi-step reasoning, scenario-based tasks | "Base on the following sprint reports, describe the challenges for project manager, team-building, psychologically, deadline-restriction, building technical doubt etc." | 3+ | GPT-4o Mini or GPT-4o |
|
42 |
+
| **8** | In-depth explanations or complex analysis | "I will give you 3 text snippets. Explain how climate change affects ocean currents, find overlapping arugments and disargreements of the authors, and use the Harvard Concept to solve the discrepancies" | 3+ | GPT-4o |
|
43 |
+
| **9** | Advanced analysis or cross-disciplinary | "Check the next 200 mails and filter out conversations between engineering and sales that are helpfull and not helpfull for the company. Give me the result as CSV-Table." | 3+ | GPT-4o |
|
44 |
+
| **10** | Expert-level analysis and synthesis | "Write a report on AI’s impact on real estate invest decision in the middle class, covering the following the main trends from 2025 to 2030 in consumption development, given by the following reports of ten different organizations. Have cultural differences in mind around the world and convert to german culture"| 3+ | GPT-4o |
|
45 |
+
|
46 |
+
|
47 |
+
|
48 |
+
## Sensitivity Scoring
|
49 |
+
|
50 |
+
The sensitivity score rates the **confidentiality** of a task on a scale from 0 to 3, where **0 represents non-sensitive, public information** (e.g., event announcements) and **3 involves highly confidential, critical data** (e.g., medical reports). Lower scores indicate content that can be shared freely, while higher scores require **secure handling** and **anonymization**. This system ensures sensitive content is properly protected, preventing any **unauthorized exposure**.
|
51 |
+
|
52 |
+
Here's the revised table with the addition of a GDPR-related example for each sensitivity level:
|
53 |
+
|
54 |
+
| **Score** | **Sensitivity and Description** | **Example 1** | **Example 2** |
|
55 |
+
|:---------:|-----------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------|
|
56 |
+
| **0** | **Public, Non-Sensitive** — Free to share; contains no confidential or personal information. | “Community Picnic this Saturday at Greenfield Park, 11 AM. RSVP by Thursday!” | "Company Press Release: New sustainability initiatives for 2024." |
|
57 |
+
| **1** | **Internal, Low Sensitivity** — For internal use only but only minor impact if disclosed. | “New office hours starting next month: 9 AM - 6 PM Mon-Thurs, half-day Fri.” | "Employee List for Training Day: Names only, no personal data." |
|
58 |
+
| **2** | **Confidential, Medium Sensitivity** — For managers or leadership; could impact finances or reputation if disclosed. | “Q3 Budget Breakdown: Marketing: $150K, R&D: $200K” | "Customer Analysis Report: Aggregate data only, segmented by region." |
|
59 |
+
| **3** | **Highly Confidential, Critical Sensitivity** — Restricted to top executives or medical professionals; severe harm if disclosed. | “Merger Negotiation: Acme to acquire 75% of BetaTech for $2.5B…” | "Employee Health Records: Only accessible to HR and necessary medical staff in compliance with GDPR." |
|
60 |
+
|
61 |
+
|
62 |
+
## Annonymization and Re-Annonymization
|
63 |
+
|
64 |
+
The model can be used locally before and after the processing data with external models
|
65 |
+
|
66 |
+
| Step | Content |
|
67 |
+
|-------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
68 |
+
| **Anonymization and Re-Anonymization** | |
|
69 |
+
| **User Input** | We have a community picnic this Saturday at Greenfield Park, 11 AM. RSVP by Thursday. Write me an e-mail announcement. |
|
70 |
+
| **Anonymized Version by Local Model** | We have a community picnic this Saturday at Maplewood Park, Late Morning. RSVP by Thursday. Write me an e-mail announcement. |
|
71 |
+
| **Processed with Main LLM (GPT-4)** | **Subject:** 🍃 Community Picnic This Saturday at Maplewood Park! 🌞 <br> <br> Hello [Community/Neighborhood] Friends, We’re excited to announce our Community Picnic happening this Saturday at Maplewood Park! This is a wonderful opportunity to relax, connect with neighbors, and enjoy some outdoor fun. We’ll gather late morning (around 10:30 AM), so bring your favorite snacks, picnic blankets, and plenty of smiles! <br> <br> **Details:** <br> 📅 **Date:** Saturday, [Exact Date] <br> 📍 **Location:** Maplewood Park <br> ⏰ **Time:** Late Morning (around 10:30 AM) <br> <br> We’ll have games, music, and a few surprises, so it’ll be a great time for all ages! Feel free to bring family, friends, and any special treats you’d like to share with the group. <br> <br> **RSVP** <br> To help us plan, please RSVP by this Thursday by replying to this email or contacting [Contact Information]. We can’t wait to see you all there and make this picnic a memorable one for our community. Don’t forget your sunscreen and a lawn chair if you’d like some extra comfort! <br> <br> **Warm regards,** [Your Name/Community Group] |
|
72 |
+
| **Entities Replaced by Local Model** | **Subject:** 🍃 Community Picnic This Saturday at Greenfield Park! 🌞 <br> <br> Hello [Community/Neighborhood] Friends, We’re excited to announce our Community Picnic happening this Saturday at Greenfield Park! This is a wonderful opportunity to relax, connect with neighbors, and enjoy some outdoor fun. We’ll gather late morning (around 10:30 AM), so bring your favorite snacks, picnic blankets, and plenty of smiles! <br> <br> **Details:** <br> 📅 **Date:** Saturday, [Exact Date] <br> 📍 **Location:** Greenfield Park <br> ⏰ **Time:** Late Morning (around 10:30 AM) <br> <br> We’ll have games, music, and a few surprises, so it’ll be a great time for all ages! Feel free to bring family, friends, and any special treats you’d like to share with the group. <br> <br> **RSVP** <br> To help us plan, please RSVP by this Thursday by replying to this email or contacting [Contact Information]. We can’t wait to see you all there and make this picnic a memorable one for our community. Don’t forget your sunscreen and a lawn chair if you’d like some extra comfort! <br> <br> **Warm regards,** [Your Name/Community Group] |
|
73 |
+
|
74 |
+
|
75 |
+
|
76 |
+
## How to Use the Model
|
77 |
+
|
78 |
+
This model provides functionalities for sensitivity assessment, complexity assesment, and entity anonymization. Each function is illustrated below with example code snippets.
|
79 |
+
|
80 |
+
<details>
|
81 |
+
<summary>Model setup and inference</summary>
|
82 |
+
|
83 |
+
```python
|
84 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
85 |
+
import torch
|
86 |
+
|
87 |
+
model_path = "metricspace/GDPR_Input_Detection_and_Anonymization"
|
88 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
89 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
90 |
+
model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch.float16 if device == "cuda" else torch.float32).to(device)
|
91 |
+
|
92 |
+
import re
|
93 |
+
import json
|
94 |
+
|
95 |
+
# Set tokenizer tokens and model padding
|
96 |
+
tokenizer.pad_token = "<|im_start|>"
|
97 |
+
tokenizer.eos_token = "<|im_end|>"
|
98 |
+
tokenizer.padding_side = "left"
|
99 |
+
model.generation_config.pad_token_id = tokenizer.pad_token_id
|
100 |
+
|
101 |
+
# Define formats for different analysis types
|
102 |
+
formats = {
|
103 |
+
"sensitivity": """<|im_start|>system\nSensitivity<|im_end|>\n<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant\n""",
|
104 |
+
"complexity": """<|im_start|>system\nComplexity<|im_end|>\n<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant\n""",
|
105 |
+
"entity_detection": """<|im_start|>system\nEntity Detection<|im_end|>\n<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant\n""",
|
106 |
+
"entity_swapping": """<|im_start|>system\nEntity Swapping<|im_end|>\n<|im_start|>user\nentities:{entities}\ntext:\n{text}<|im_end|>\n<|im_start|>assistant\n"""
|
107 |
+
}
|
108 |
+
|
109 |
+
def model_inference(text, mode="anonymization", max_new_tokens=50, config=None, entity_mapping=None):
|
110 |
+
if mode not in formats and mode != "anonymization":
|
111 |
+
raise ValueError("Invalid mode. Choose from 'sensitivity', 'complexity', 'entity_detection', 'anonymization'.")
|
112 |
+
|
113 |
+
|
114 |
+
# Configuration for anonymization
|
115 |
+
# The `config` dictionary specifies the anonymization behavior for each type of entity detected.
|
116 |
+
# Each key in `config` represents an entity type (e.g., "LOC" for location, "PERSON" for personal names),
|
117 |
+
# and the value assigned to that key determines how entities of that type should be anonymized:
|
118 |
+
#
|
119 |
+
# - "RANDOM": Replaces the entity with a randomly selected placeholder.
|
120 |
+
# - "GENERAL LOW", "GENERAL MEDIUM", "GENERAL HIGH": Replaces the entity with a generalized label,
|
121 |
+
# with the intensity level (LOW, MEDIUM, HIGH) controlling the specificity. For example,
|
122 |
+
# "GENERAL LOW" might use a more specific label ("Local Park") while "GENERAL HIGH" would use
|
123 |
+
# a broader label ("Recreational Area").
|
124 |
+
#
|
125 |
+
# This allows fine-grained control over anonymization, ensuring that different types of sensitive
|
126 |
+
# information can be replaced in ways that are appropriate for the context. For example:
|
127 |
+
# - "LOC": "RANDOM" replaces any detected location with a random placeholder.
|
128 |
+
# - "DATETIME": "GENERAL LOW" uses a lower-intensity generalization for dates and times.
|
129 |
+
#
|
130 |
+
# This flexibility enables custom anonymization policies to suit different privacy or obfuscation needs.
|
131 |
+
|
132 |
+
if config is None:
|
133 |
+
config = {
|
134 |
+
"LOC": "RANDOM",
|
135 |
+
"PERSON": "RANDOM",
|
136 |
+
"DEM": "RANDOM",
|
137 |
+
"CODE": "RANDOM",
|
138 |
+
"ORG": "GENERAL MEDIUM",
|
139 |
+
"DATETIME": "GENERAL LOW",
|
140 |
+
"QUANTITY": "RANDOM",
|
141 |
+
"MISC": "RANDOM",
|
142 |
+
}
|
143 |
+
|
144 |
+
# Anonymization Mode
|
145 |
+
if mode == "anonymization":
|
146 |
+
# Step 1: Entity detection
|
147 |
+
detection_prompt = formats["entity_detection"].format(text=text)
|
148 |
+
detection_inputs = tokenizer(detection_prompt, return_tensors="pt").to(device)
|
149 |
+
detection_output = model.generate(
|
150 |
+
**detection_inputs,
|
151 |
+
max_new_tokens=max_new_tokens,
|
152 |
+
use_cache=True,
|
153 |
+
eos_token_id=151645
|
154 |
+
)
|
155 |
+
detection_text = tokenizer.decode(detection_output[0], skip_special_tokens=True)
|
156 |
+
detected_entities = postprocess_entity_recognition(detection_text)
|
157 |
+
|
158 |
+
# Step 2: Select entities based on config
|
159 |
+
selected_entities = select_entities_based_on_json(detected_entities, config)
|
160 |
+
entities_str = "\n".join([f"{entity} : {label}" for entity, label in selected_entities])
|
161 |
+
|
162 |
+
# Step 3: Entity swapping for anonymization
|
163 |
+
swapping_prompt = formats["entity_swapping"].format(entities=entities_str, text=text)
|
164 |
+
swapping_inputs = tokenizer(swapping_prompt, return_tensors="pt").to(device)
|
165 |
+
swapping_output = model.generate(
|
166 |
+
**swapping_inputs,
|
167 |
+
max_new_tokens=max_new_tokens,
|
168 |
+
use_cache=True,
|
169 |
+
eos_token_id=151645
|
170 |
+
)
|
171 |
+
|
172 |
+
anonymized_text = tokenizer.decode(swapping_output[0], skip_special_tokens=True)
|
173 |
+
anonymized_text = anonymized_text.split("assistant\n", 1)[-1].strip() # Extract only the assistant's response
|
174 |
+
|
175 |
+
return anonymized_text, detected_entities
|
176 |
+
|
177 |
+
# Entity Restoration Mode using entity_swapping
|
178 |
+
elif mode == "entity_swapping" and entity_mapping:
|
179 |
+
# Aggregate RANDOM and GENERAL replacements for restoration
|
180 |
+
reversed_entities = []
|
181 |
+
for original, details in entity_mapping.items():
|
182 |
+
# Include RANDOM replacement
|
183 |
+
reversed_entities.append(f"{details['RANDOM']} : {original}")
|
184 |
+
# Include GENERAL replacements
|
185 |
+
for general_label, _ in details["GENERAL"]:
|
186 |
+
reversed_entities.append(f"{general_label} : {original}")
|
187 |
+
|
188 |
+
# Combine all replacement mappings for the prompt
|
189 |
+
reversed_entities_str = "\n".join(reversed_entities)
|
190 |
+
|
191 |
+
# Create the swapping prompt with the aggregated reversed mappings
|
192 |
+
swapping_prompt = formats["entity_swapping"].format(entities=reversed_entities_str, text=text)
|
193 |
+
swapping_inputs = tokenizer(swapping_prompt, return_tensors="pt").to(device)
|
194 |
+
swapping_output = model.generate(
|
195 |
+
**swapping_inputs,
|
196 |
+
max_new_tokens=max_new_tokens,
|
197 |
+
use_cache=True,
|
198 |
+
eos_token_id=151645
|
199 |
+
)
|
200 |
+
|
201 |
+
# Decode and extract the restored text
|
202 |
+
output_text = tokenizer.decode(swapping_output[0], skip_special_tokens=True)
|
203 |
+
output_text = output_text.split("assistant\n", 1)[-1].strip() # Extract only the assistant's response
|
204 |
+
|
205 |
+
return output_text
|
206 |
+
|
207 |
+
# Other modes (sensitivity, complexity, entity_detection)
|
208 |
+
else:
|
209 |
+
prompt = formats[mode].format(text=text)
|
210 |
+
model_inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
211 |
+
generation_output = model.generate(
|
212 |
+
**model_inputs,
|
213 |
+
max_new_tokens=max_new_tokens,
|
214 |
+
use_cache=True,
|
215 |
+
eos_token_id=151645
|
216 |
+
)
|
217 |
+
full_output = tokenizer.decode(generation_output[0], skip_special_tokens=True)
|
218 |
+
|
219 |
+
if mode in ["sensitivity", "complexity"]:
|
220 |
+
assistant_text = full_output.split("assistant\n", 1)[-1].strip()
|
221 |
+
return assistant_text
|
222 |
+
elif mode == "entity_detection":
|
223 |
+
return postprocess_entity_recognition(full_output)
|
224 |
+
|
225 |
+
# Function to parse entity detection output
|
226 |
+
def postprocess_entity_recognition(detection_output: str) -> dict:
|
227 |
+
output_json = {}
|
228 |
+
entity_pattern = re.compile(
|
229 |
+
r'(?P<entity>[\w\s]+)--(?P<type>[\w]+)--(?P<random>[\w\s]+)--(?P<generalizations>.+)'
|
230 |
+
)
|
231 |
+
generalization_pattern = re.compile(r'(\d+)::([\w\s]+)')
|
232 |
+
|
233 |
+
lines = detection_output.strip().split("\n")
|
234 |
+
for line in lines:
|
235 |
+
match = entity_pattern.search(line)
|
236 |
+
if match:
|
237 |
+
entity_name = match.group("entity").strip()
|
238 |
+
entity_type = match.group("type").strip()
|
239 |
+
random_replacement = match.group("random").strip()
|
240 |
+
|
241 |
+
generalizations = []
|
242 |
+
for gen_match in generalization_pattern.findall(match.group("generalizations")):
|
243 |
+
score, label = gen_match
|
244 |
+
generalizations.append([label.strip(), score.strip()])
|
245 |
+
|
246 |
+
output_json[entity_name] = {
|
247 |
+
"TYPE": entity_type,
|
248 |
+
"RANDOM": random_replacement,
|
249 |
+
"GENERAL": generalizations
|
250 |
+
}
|
251 |
+
return output_json
|
252 |
+
|
253 |
+
# Function to select entities based on config
|
254 |
+
def select_entities_based_on_json(prediction_json, entity_json):
|
255 |
+
entities = []
|
256 |
+
for key, value in prediction_json.items():
|
257 |
+
entity_type = value["TYPE"]
|
258 |
+
if entity_type in entity_json:
|
259 |
+
anonymization_type = entity_json[entity_type]
|
260 |
+
if anonymization_type == "RANDOM":
|
261 |
+
entities.append([key, value["RANDOM"]])
|
262 |
+
elif "GENERAL" in anonymization_type:
|
263 |
+
intensity = anonymization_type.split(" ")[1]
|
264 |
+
if intensity == "LOW" and value["GENERAL"]:
|
265 |
+
entities.append([key, value["GENERAL"][0][0]])
|
266 |
+
elif intensity == "MEDIUM":
|
267 |
+
for gen in value["GENERAL"]:
|
268 |
+
if int(gen[1]) >= 4:
|
269 |
+
entities.append([key, gen[0]])
|
270 |
+
break
|
271 |
+
elif intensity == "HIGH":
|
272 |
+
if value["GENERAL"]:
|
273 |
+
entities.append([key, value["GENERAL"][0][0]])
|
274 |
+
return entities
|
275 |
+
```
|
276 |
+
</details>
|
277 |
+
|
278 |
+
### 1. Sensitivity and Complexity Analysis
|
279 |
+
|
280 |
+
Example text
|
281 |
+
```
|
282 |
+
We have a community picnic this Saturday at Greenfield Park, 11 AM. RSVP by Thursday, Write me an e-mail annoucment!
|
283 |
+
```
|
284 |
+
|
285 |
+
The sensitivity analysis feature evaluates the sensitivity of a given text and the complexitivity feature rates the complexity.
|
286 |
+
```python
|
287 |
+
text = "We have a community picnic this Saturday at Greenfield Park, 11 AM. RSVP by Thursday, Write me an e-mail annoucment!"
|
288 |
+
|
289 |
+
# Generate sensitivity score
|
290 |
+
sensitivity_score = model_inference(text, mode="sensitivity")
|
291 |
+
print(f"Sensitivity Score: {sensitivity_score}" "\n")
|
292 |
+
|
293 |
+
# Generate complexity score
|
294 |
+
complexity_score = model_inference(text, mode="complexity")
|
295 |
+
print(f"Complexity: {complexity_score}" "\n")
|
296 |
+
```
|
297 |
+
|
298 |
+
Output
|
299 |
+
```
|
300 |
+
Sensitivity Score: 0
|
301 |
+
Complexity Score: 3
|
302 |
+
```
|
303 |
+
|
304 |
+
### 3. Anonymization and Re-Anonymization
|
305 |
+
|
306 |
+
To protect sensitive information, the model detects specific entities in the text and anonymizes them based on a pre-configured setting.
|
307 |
+
|
308 |
+
|
309 |
+
```python
|
310 |
+
# Anonymize the text
|
311 |
+
anonymized_text, entity_mapping = model_inference(text, mode="anonymization")
|
312 |
+
print(f"Anonymized Text: {anonymized_text}\n")
|
313 |
+
|
314 |
+
# Restore the original text
|
315 |
+
restored_text = model_inference(anonymized_text, mode="entity_swapping", entity_mapping=entity_mapping)
|
316 |
+
print(f"Restored Text: {restored_text}")
|
317 |
+
```
|
318 |
+
|
319 |
+
Output
|
320 |
+
```
|
321 |
+
Anonymized Text: We have a community picnic this Saturday at Maplewood Park, Late Morning. RSVP by Thursday, Write me an e-mail announcement.
|
322 |
+
|
323 |
+
Restored Text: We have a community picnic this Saturday at Greenfield Park, 11 AM. RSVP by Thursday, Write me an e-mail announcement.
|
324 |
+
```
|
325 |
+
|
326 |
+
This is how the stored entitiy maps looks like
|
327 |
+
```python
|
328 |
+
print(f"{json.dumps(entity_mapping, indent=4)}")
|
329 |
+
```
|
330 |
+
Output
|
331 |
+
```
|
332 |
+
{
|
333 |
+
"Greenfield Park": {
|
334 |
+
"TYPE": "LOC",
|
335 |
+
"RANDOM": "Maplewood Park",
|
336 |
+
"GENERAL": [
|
337 |
+
[
|
338 |
+
"Local Park",
|
339 |
+
"3"
|
340 |
+
],
|
341 |
+
[
|
342 |
+
"Public Park",
|
343 |
+
"5"
|
344 |
+
],
|
345 |
+
[
|
346 |
+
"Recreational Area",
|
347 |
+
"7"
|
348 |
+
]
|
349 |
+
]
|
350 |
+
},
|
351 |
+
"11 AM": {
|
352 |
+
"TYPE": "DATETIME",
|
353 |
+
"RANDOM": "1 PM",
|
354 |
+
"GENERAL": [
|
355 |
+
[
|
356 |
+
"Late Morning",
|
357 |
+
"2"
|
358 |
+
],
|
359 |
+
[
|
360 |
+
"A",
|
361 |
+
"4"
|
362 |
+
]
|
363 |
+
]
|
364 |
+
}
|
365 |
+
}
|
366 |
+
```
|
367 |
+
|
368 |
+
Normally you would process the annonymized version with a LLM and than reanonymize the result back.
|
369 |
+
|
370 |
+
|
371 |
+
|
372 |
+
## Limitations
|
373 |
+
|
374 |
+
For **complexity and sensitivity scoring**, the model can process inputs up to **2,048 tokens**. However, for **entity detection**, the combined limit for input and output is **3,000 tokens**. If a text is too long or contains numerous entities, this limit may be exceeded, which could result in truncated outputs or inconsistent behavior. To ensure accurate results, it's recommended to keep input lengths within these token limits.
|
375 |
+
|
376 |
+
## Language Support
|
377 |
+
|
378 |
+
The model supports 29 language. It was trained with a mixture of (80% english examples, 20% multilanguage examples)
|
379 |
+
|
380 |
+
## Licence
|
381 |
+
|
382 |
+
Apache license 2.0
|