Update app.py
Browse files114 unmodified lines1151161171181191201211221231245 unmodified lines1301311321331341351361371381391401411421431447 unmodified lines1521531541551561571581591601611621631641651661671681691701711721738 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902913 unmodified lines2952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263276 unmodified lines334335336337338339114 unmodified linesplaceholder = config["placeholder"]for match in re.finditer(pattern, text, re.IGNORECASE):# Avoid duplicate detections for overlapping patternsvalue = match.group()# Skip if this looks like a false positiveif pii_type == "TC_KIMLIK" and len(value) != 11:continue5 unmodified linesconfidence="HIGH" if len(value) > 8 else "MEDIUM"))# Sort by position (reverse) for correct replacementdetections.sort(key=lambda x: x.start, reverse=True)# Redact in reverse order to maintain positionsfor det in detections:placeholder = self.PATTERNS[det.type]["placeholder"]redacted_text = redacted_text[:det.start] + placeholder + redacted_text[det.end:]# Re-sort for display (by position, ascending)detections.sort(key=lambda x: x.start)return detections, redacted_text7 unmodified linesdef analyze_text(text: str) -> Tuple[str, str, str]:"""Main analysis function for Gradio interface.Returns:Tuple of (redacted_text, detection_report, stats)"""if not text.strip():return "", "⚠️ Please enter some text to analyze.", ""detections, redacted_text = detector.detect(text)if not detections:return text, "✅ No sensitive information detected.", "**0** PII entities found"# Build detection reportreport_lines = ["### 🔍 Detected Entities\n"]# Group by typeby_type = {}for det in detections:if det.type not in by_type:8 unmodified linesreport_lines.append(f"- `{masked_value}` (confidence: {item.confidence})")report = "\n".join(report_lines)# Statsstats = f"**{len(detections)}** PII entities found across **{len(by_type)}** categories"return redacted_text, report, stats# Example texts for users to tryEXAMPLES = [["""Hi, my name is John Smith and my email is john.smith@company.com.You can reach me at +1-555-123-4567. My SSN is 123-45-6789."""],["""Customer Order #12345Name: Jane DoeEmail: jane.doe@example.orgPhone: (555) 987-6543Credit Card: 4532015112830366Shipping Address: 123 Main St, New York, NY 10001"""],["""API Configuration:api_key = "sk-1234567890abcdefghijklmnopqrstuvwxyz"AWS_ACCESS_KEY: AKIAIOSFODNN7EXAMPLEpassword: "super_secret_123"database_url: postgres://user:pass@192.168.1.100:5432/db"""],["""Merhaba, ben Ahmet Yılmaz. TC Kimlik numaram 12345678901.Telefon: 0532 123 45 67IBAN: TR330006100519786457841326Email: ahmet.yilmaz@sirket.com.tr"""],]# Custom CSScustom_css = """.gradio-container {font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;}.detection-box {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);border-radius: 12px;padding: 20px;}footer {visibility: hidden;}"""# Build the interfacewith gr.Blocks(css=custom_css, title="TSZ - Thyris Safe Zone Demo") as demo:# Headergr.Markdown("""# 🛡️ TSZ (Thyris Safe Zone) - Interactive Demo**TSZ** is an open-source PII detection and guardrails engine that prevents sensitive datafrom leaking to LLMs and third-party APIs. This demo showcases its core detection capabilities.<div style="display: flex; gap: 10px; margin: 10px 0;"><a href="https://github.com/thyrisAI/safe-zone" target="_blank"><img src="https://img.shields.io/badge/GitHub-Repository-black?logo=github" alt="GitHub"></a><a href="https://thyris.ai" target="_blank"><img src="https://img.shields.io/badge/Website-thyris.ai-blue" alt="Website"></a><a href="https://github.com/thyrisAI/safe-zone/blob/main/LICENSE" target="_blank"><img src="https://img.shields.io/badge/License-Apache%202.0-green" alt="License"></a></div>""")with gr.Row():with gr.Column(scale=1):# Inputinput_text = gr.Textbox(label="📝 Input Text",placeholder="Paste text containing emails, phone numbers, credit cards, API keys, passwords, etc...",lines=10,max_lines=20)analyze_btn = gr.Button("🔍 Analyze & Redact", variant="primary", size="lg")gr.Markdown("### 📋 Try These Examples")gr.Examples(examples=EXAMPLES,inputs=input_text,label="")with gr.Column(scale=1):# Outputsstats_output = gr.Markdown(label="Statistics")redacted_output = gr.Textbox(label="🔒 Redacted Output (Safe to send to LLMs)",lines=10,max_lines=20,interactive=False)detection_report = gr.Markdown(label="Detection Report")# Supported types infogr.Markdown("""---### 🎯 Supported Detection Types| Category | Types ||----------|-------|3 unmodified lines---### 🚀 Get the Full VersionThis demo uses a simplified detection engine. The full **TSZ** includes:- ✅ More comprehensive pattern matching with validators- ✅ Configurable guardrails and policies- ✅ Allowlist/blocklist management- ✅ REST API with hot-reloadable rules- ✅ High-performance Go implementation with Redis caching- ✅ Docker deployment ready**Install TSZ:**```bashgit clone https://github.com/thyrisAI/safe-zone.gitcd safe-zonedocker-compose up -d```---<p style="text-align: center; color: #666;">Built with ❤️ by <a href="https://thyris.ai" target="_blank">Thyris.AI</a> |Licensed under Apache 2.0</p>""")# Event handlersanalyze_btn.click(fn=analyze_text,inputs=[input_text],6 unmodified linesoutputs=[redacted_output, detection_report, stats_output])# Launchif __name__ == "__main__":demo.launch()114 unmodified lines1151161171181191201211225 unmodified lines1281291301311321331341351361371381397 unmodified lines1471481491501511521531541551561571581591601611621638 unmodified lines1721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282293 unmodified lines2332342352362372382392402412422432442452462472482492502512522532542556 unmodified lines262263264265266114 unmodified linesplaceholder = config["placeholder"]for match in re.finditer(pattern, text, re.IGNORECASE):value = match.group()if pii_type == "TC_KIMLIK" and len(value) != 11:continue5 unmodified linesconfidence="HIGH" if len(value) > 8 else "MEDIUM"))detections.sort(key=lambda x: x.start, reverse=True)for det in detections:placeholder = self.PATTERNS[det.type]["placeholder"]redacted_text = redacted_text[:det.start] + placeholder + redacted_text[det.end:]detections.sort(key=lambda x: x.start)return detections, redacted_text7 unmodified linesdef analyze_text(text: str) -> Tuple[str, str, str]:"""Main analysis function for Gradio interface."""if not text.strip():return "", "Please enter some text to analyze.", ""detections, redacted_text = detector.detect(text)if not detections:return text, "No sensitive information detected.", "**0** PII entities found"report_lines = ["### Detected Entities\n"]by_type = {}for det in detections:if det.type not in by_type:8 unmodified linesreport_lines.append(f"- `{masked_value}` (confidence: {item.confidence})")report = "\n".join(report_lines)stats = f"**{len(detections)}** PII entities found across **{len(by_type)}** categories"return redacted_text, report, statsEXAMPLES = [["Hi, my name is John Smith and my email is john.smith@company.com. You can reach me at +1-555-123-4567. My SSN is 123-45-6789."],["Customer Order #12345\nName: Jane Doe\nEmail: jane.doe@example.org\nPhone: (555) 987-6543\nCredit Card: 4532015112830366"],["API Configuration:\napi_key = \"sk-1234567890abcdefghijklmnopqrstuvwxyz\"\nAWS_ACCESS_KEY: AKIAIOSFODNN7EXAMPLE\npassword: \"super_secret_123\""],["Merhaba, ben Ahmet Yilmaz. TC Kimlik numaram 12345678901.\nTelefon: 0532 123 45 67\nIBAN: TR330006100519786457841326"],]with gr.Blocks(title="TSZ - Thyris Safe Zone Demo") as demo:gr.Markdown("""# TSZ (Thyris Safe Zone) - Interactive Demo**TSZ** is an open-source PII detection and guardrails engine that prevents sensitive datafrom leaking to LLMs and third-party APIs.[GitHub](https://github.com/thyrisAI/safe-zone) | [Website](https://thyris.ai) | Apache 2.0 License""")with gr.Row():with gr.Column():input_text = gr.Textbox(label="Input Text",placeholder="Paste text containing emails, phone numbers, credit cards, API keys, passwords, etc...",lines=8)analyze_btn = gr.Button("Analyze & Redact", variant="primary")gr.Markdown("### Try These Examples")gr.Examples(examples=EXAMPLES,inputs=input_text)with gr.Column():stats_output = gr.Markdown(label="Statistics")redacted_output = gr.Textbox(label="Redacted Output (Safe to send to LLMs)",lines=8,interactive=False)detection_report = gr.Markdown(label="Detection Report")gr.Markdown("""---### Supported Detection Types| Category | Types ||----------|-------|3 unmodified lines---### Get the Full VersionThis demo uses a simplified detection engine. The full **TSZ** includes:- More comprehensive pattern matching with validators- Configurable guardrails and policies- REST API with hot-reloadable rules- High-performance Go implementation with Redis caching```bashgit clone https://github.com/thyrisAI/safe-zone.gitcd safe-zonedocker-compose up -d```Built by [Thyris.AI](https://thyris.ai)""")analyze_btn.click(fn=analyze_text,inputs=[input_text],6 unmodified linesoutputs=[redacted_output, detection_report, stats_output])if __name__ == "__main__":demo.launch()
app.py+27-100