awacke1 commited on
Commit
e8c756f
·
verified ·
1 Parent(s): c1468fc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -19
app.py CHANGED
@@ -10,6 +10,7 @@ from PyPDF2 import PdfReader, PdfWriter
10
  from presidio_analyzer import AnalyzerEngine, RecognizerRegistry, PatternRecognizer, RecognizerResult
11
  from presidio_anonymizer import AnonymizerEngine
12
  from presidio_anonymizer.entities import OperatorConfig
 
13
 
14
  st.set_page_config(page_title="Presidio PHI De-identification", layout="wide", initial_sidebar_state="expanded", menu_items={"About": "https://microsoft.github.io/presidio/"})
15
  dotenv.load_dotenv()
@@ -44,14 +45,10 @@ def analyzer_engine(model_family: str, model_path: str) -> AnalyzerEngine:
44
 
45
  def get_supported_entities(model_family: str, model_path: str) -> list[str]:
46
  """📋 Lists what secrets we’re hunting—PHI beware!"""
47
- if model_family.lower() == "huggingface":
48
- return ["PERSON", "LOCATION", "ORGANIZATION", "DATE_TIME"]
49
- elif model_family.lower() == "flair":
50
- return ["PERSON", "LOCATION", "ORGANIZATION"]
51
- return ["PERSON", "LOCATION", "ORGANIZATION"]
52
 
53
  # Feature Spotlight: 🕵️‍♂️ The Great PHI Hunt Begins!
54
- # With a flick of the wrist, we summon models to sniff out sensitive data in PDFs, making privacy a breeze! 😎
55
 
56
  def analyze(analyzer: AnalyzerEngine, text: str, entities: list[str], language: str, score_threshold: float, return_decision_process: bool, allow_list: list[str], deny_list: list[str]) -> list[RecognizerResult]:
57
  """🦸 Swoops in to spot PHI with laser precision!"""
@@ -80,14 +77,15 @@ def create_ad_hoc_deny_list_recognizer(deny_list: list[str] = None) -> PatternRe
80
  return PatternRecognizer(supported_entity="GENERIC_PII", deny_list=deny_list)
81
 
82
  def save_pdf(pdf_input) -> str:
83
- """💾 Drops PDFs onto disk like hot cakes!"""
84
- original_name = pdf_input.name
85
- with open(original_name, "wb") as f:
86
- f.write(pdf_input.read())
87
- return original_name
 
88
 
89
  # Feature Spotlight: 📄 PDF Magic Unleashed!
90
- # Upload a PDF, zap the PHI, and grab a shiny new file—all with a timestamp swagger! ✨
91
 
92
  def read_pdf(pdf_path: str) -> str:
93
  """📖 Slurps up PDF text like a thirsty camel!"""
@@ -111,13 +109,13 @@ model_list = [
111
  ("HuggingFace/obi/deid_roberta_i2b2", "https://huggingface.co/obi/deid_roberta_i2b2"),
112
  ("HuggingFace/StanfordAIMI/stanford-deidentifier-base", "https://huggingface.co/StanfordAIMI/stanford-deidentifier-base"),
113
  ]
114
- st_model = st.sidebar.selectbox("NER model package", [model[0] for model in model_list], index=0, help="Pick your PHI-hunting hero!")
115
- st.sidebar.markdown(f"[View model on HuggingFace]({next(url for model, url in model_list if model == st_model)})")
116
  st_model_package = st_model.split("/")[0]
117
  st_model = st_model if st_model_package.lower() != "huggingface" else "/".join(st_model.split("/")[1:])
118
  analyzer_params = (st_model_package, st_model)
119
  st.sidebar.warning("Models may take a sec to wake up!")
120
- st_operator = st.sidebar.selectbox("De-identification approach", ["replace", "redact", "mask"], index=0, help="Choose how to zap PHI!")
121
  st_threshold = st.sidebar.slider("Acceptance threshold", 0.0, 1.0, 0.35)
122
  st_return_decision_process = st.sidebar.checkbox("Add analysis explanations", False)
123
  with st.sidebar.expander("Allowlists and denylists"):
@@ -132,8 +130,6 @@ with col1:
132
  if uploaded_file:
133
  try:
134
  pdf_path = save_pdf(uploaded_file)
135
- if not pdf_path:
136
- raise ValueError("PDF save flopped!")
137
  text = read_pdf(pdf_path)
138
  if not text:
139
  raise ValueError("No text in that PDF!")
@@ -157,8 +153,6 @@ with col1:
157
  timestamp = get_timestamp_prefix()
158
  output_filename = f"{timestamp}_{uploaded_file.name}"
159
  pdf_output = create_pdf(anonymized_result.text, pdf_path, output_filename)
160
- if not pdf_output:
161
- raise ValueError("PDF creation tanked!")
162
  with open(output_filename, "rb") as f:
163
  pdf_bytes = f.read()
164
  b64 = base64.b64encode(pdf_bytes).decode()
 
10
  from presidio_analyzer import AnalyzerEngine, RecognizerRegistry, PatternRecognizer, RecognizerResult
11
  from presidio_anonymizer import AnonymizerEngine
12
  from presidio_anonymizer.entities import OperatorConfig
13
+ import tempfile
14
 
15
  st.set_page_config(page_title="Presidio PHI De-identification", layout="wide", initial_sidebar_state="expanded", menu_items={"About": "https://microsoft.github.io/presidio/"})
16
  dotenv.load_dotenv()
 
45
 
46
  def get_supported_entities(model_family: str, model_path: str) -> list[str]:
47
  """📋 Lists what secrets we’re hunting—PHI beware!"""
48
+ return ["PERSON", "LOCATION", "ORGANIZATION", "DATE_TIME"] if model_family.lower() == "huggingface" else ["PERSON", "LOCATION", "ORGANIZATION"]
 
 
 
 
49
 
50
  # Feature Spotlight: 🕵️‍♂️ The Great PHI Hunt Begins!
51
+ # Summon models to sniff out sensitive data in PDFs with ninja stealth! 😎
52
 
53
  def analyze(analyzer: AnalyzerEngine, text: str, entities: list[str], language: str, score_threshold: float, return_decision_process: bool, allow_list: list[str], deny_list: list[str]) -> list[RecognizerResult]:
54
  """🦸 Swoops in to spot PHI with laser precision!"""
 
77
  return PatternRecognizer(supported_entity="GENERIC_PII", deny_list=deny_list)
78
 
79
  def save_pdf(pdf_input) -> str:
80
+ """💾 Drops PDFs into a cozy temp hideout!"""
81
+ if pdf_input.size > 200 * 1024 * 1024:
82
+ raise ValueError("PDF exceeds 200MB limit")
83
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf", dir="/tmp") as tmp:
84
+ tmp.write(pdf_input.read())
85
+ return tmp.name
86
 
87
  # Feature Spotlight: 📄 PDF Magic Unleashed!
88
+ # Zap PHI from PDFs and sling back a shiny, safe file with timestamp swagger! ✨
89
 
90
  def read_pdf(pdf_path: str) -> str:
91
  """📖 Slurps up PDF text like a thirsty camel!"""
 
109
  ("HuggingFace/obi/deid_roberta_i2b2", "https://huggingface.co/obi/deid_roberta_i2b2"),
110
  ("HuggingFace/StanfordAIMI/stanford-deidentifier-base", "https://huggingface.co/StanfordAIMI/stanford-deidentifier-base"),
111
  ]
112
+ st_model = st.sidebar.selectbox("NER model package", [m[0] for m in model_list], 0, help="Pick your PHI-hunting hero!")
113
+ st.sidebar.markdown(f"[View model on HuggingFace]({next(url for m, url in model_list if m == st_model)})")
114
  st_model_package = st_model.split("/")[0]
115
  st_model = st_model if st_model_package.lower() != "huggingface" else "/".join(st_model.split("/")[1:])
116
  analyzer_params = (st_model_package, st_model)
117
  st.sidebar.warning("Models may take a sec to wake up!")
118
+ st_operator = st.sidebar.selectbox("De-identification approach", ["replace", "redact", "mask"], 0, help="Choose how to zap PHI!")
119
  st_threshold = st.sidebar.slider("Acceptance threshold", 0.0, 1.0, 0.35)
120
  st_return_decision_process = st.sidebar.checkbox("Add analysis explanations", False)
121
  with st.sidebar.expander("Allowlists and denylists"):
 
130
  if uploaded_file:
131
  try:
132
  pdf_path = save_pdf(uploaded_file)
 
 
133
  text = read_pdf(pdf_path)
134
  if not text:
135
  raise ValueError("No text in that PDF!")
 
153
  timestamp = get_timestamp_prefix()
154
  output_filename = f"{timestamp}_{uploaded_file.name}"
155
  pdf_output = create_pdf(anonymized_result.text, pdf_path, output_filename)
 
 
156
  with open(output_filename, "rb") as f:
157
  pdf_bytes = f.read()
158
  b64 = base64.b64encode(pdf_bytes).decode()