DeepMount00 commited on
Commit
007db21
·
verified ·
1 Parent(s): 7a0433f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -0
app.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+
4
+ # Model names (keeping it programmatic)
5
+ model_names = [
6
+ r"DeepMount00/Italian_NER_XXL_v2",
7
+ "DeepMount00/Italian_NER_XXL"
8
+ ]
9
+
10
+ # Example texts
11
+ example_texts = {
12
+ "Example 1 - Simple": "Aspetterò Marco per un altro quarto d'ora. Con questo ritardo rischio di prendere una multa di 40 euro.",
13
+ "Example 2 - Personal Info": "Il Sig. Mario Rossi, nato il 15/03/1980, codice fiscale RSSMRI80C15H264Z, residente in Via Garibaldi 12, 20017 Rho (MI), Italia, di professione Ingegnere Informatico e di 45 anni, stato civile Coniugato in regime di Separazione dei Beni, ha avviato una contestazione formale nei confronti della società TechSolutions S.p.A. con P.IVA IT09876543210, avente sede legale in Viale dell'Innovazione 50, 10121 Torino (TO).",
14
+ "Example 3 - Financial": "La disputa riguarda l'acquisto di un dispositivo \"Omega Device\" avvenuto in data 10/01/2025 alle ore 16:45 per un importo totale di € 1.599,00. Il pagamento è stato effettuato tramite carta di credito Visa, numero 4929 **** **** 8888, con codice di sicurezza 123, addebitato sul conto numero 1000/56789 presso Banca Sella identificata dal codice BIC SELBIT2BXXX e associato all'IBAN IT60 X 05428 11101 000000123456. Un tentativo precedente di pagamento tramite assegno n. 987654321 emesso da Deutsche Bank era stato respinto.",
15
+ "Example 4 - Technical": "Il dispositivo, con numero IMEI 358001223344556, presentava malfunzionamenti durante la connessione dalla rete domestica del Sig. Rossi, identificata dall'IP 88.149.200.15 e talvolta dall'IPV6 2001:0db8:85a3:0000:1111:8a2e:0370:7334. Il log del sistema ha registrato il seguente user agent: Mozilla/5.0 (Linux; Android 13; SM-G991B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36. L'indirizzo MAC del router è 0A:1B:2C:3D:4E:FF. La segnalazione è stata inviata tramite il portale web all'URL https://www.google.com/search?q=https://support.techsolutions.example.com/case/98765. Per accedere all'area riservata, è stata richiesta la modifica della password \"N3wP@ssword!24\" e del PIN 8855.",
16
+ "Example 5 - Legal": "Il Sig. Rossi è assistito dall'Avv. Luca Verdi dello studio legale Verdi & Associati. La pratica è stata depositata presso il Tribunale di Milano e fa riferimento alla Legge 24/2017 sulla responsabilità del produttore, citando la Sentenza n. 123/2024 del medesimo tribunale. Il documento di reclamo porta il numero ID-RECLAMO-TS-005.",
17
+ "Example 6 - Medical": "A causa dello stress derivante dalla situazione, il Sig. Rossi ha consultato il proprio medico, il quale ha diagnosticato una forma lieve di insonnia. È stato prescritto un blando sedativo, Valeriana Complex in compresse, dosaggio: 1 compressa, frequenza: una volta al giorno prima di coricarsi, durata: per 3 settimane. Il medico ha fatto riferimento alla Cartella Clinica n. 789/AZ e alla Storia Clinica del paziente. Il farmaco ha una forza definita \"blanda\".",
18
+ "Example 7 - Property": "Per completezza, si segnala che il Sig. Rossi possiede un immobile a Como, i cui dati catastali sono: Foglio 15, Particella 210, Mappale 450, Subalterno 3. Possiede inoltre una vettura con targa GE543PL. La sua licenza di guida ha numero MI1234567X. Il suo recapito email è mario.rossi.mr@provider.com e il suo numero di telefono è +39 347 1122334."
19
+ }
20
+
21
+ # Default example for usage examples
22
+ default_example = example_texts["Example 1 - Simple"]
23
+
24
+ # Programmatically build the model info dict
25
+ model_info = {
26
+ model_name: {
27
+ "link": f"https://huggingface.co/{model_name}",
28
+ "usage": f"""from transformers import pipeline
29
+ ner = pipeline("ner", model="{model_name}", grouped_entities=True)
30
+ result = ner("{default_example}")
31
+ print(result)""",
32
+ }
33
+ for model_name in model_names
34
+ }
35
+
36
+ # Load models into a dictionary programmatically
37
+ models = {
38
+ model_name: pipeline("ner", model=model_name, grouped_entities=True)
39
+ for model_name in model_names
40
+ }
41
+
42
+
43
+ # Function to run NER on input text with a specific model
44
+ def analyze_text_with_model(text, model_name):
45
+ ner = models[model_name]
46
+ ner_results = ner(text)
47
+ highlighted_text = []
48
+ last_idx = 0
49
+ for entity in ner_results:
50
+ start = entity["start"]
51
+ end = entity["end"]
52
+ label = entity["entity_group"]
53
+ # Add non-entity text
54
+ if start > last_idx:
55
+ highlighted_text.append((text[last_idx:start], None))
56
+ # Add entity text
57
+ highlighted_text.append((text[start:end], label))
58
+ last_idx = end
59
+ # Add any remaining text after the last entity
60
+ if last_idx < len(text):
61
+ highlighted_text.append((text[last_idx:], None))
62
+ return highlighted_text
63
+
64
+
65
+ # Run both models and return results
66
+ def analyze_text_with_both_models(text):
67
+ results = []
68
+ for model_name in model_names:
69
+ results.append(analyze_text_with_model(text, model_name))
70
+ return results
71
+
72
+
73
+ # Function to update text input based on example selection
74
+ def update_example(example_name):
75
+ return example_texts[example_name]
76
+
77
+
78
+ with gr.Blocks() as demo:
79
+ gr.Markdown("# Named Entity Recognition (NER) Model Comparison")
80
+
81
+ # Example selector
82
+ example_selector = gr.Radio(
83
+ choices=list(example_texts.keys()),
84
+ label="Select Example Text",
85
+ value="Example 1 - Simple"
86
+ )
87
+
88
+ # Textbox for input text
89
+ text_input = gr.Textbox(
90
+ label="Enter Text",
91
+ lines=10, # Increased number of lines to better display the longer example
92
+ value=example_texts["Example 1 - Simple"],
93
+ )
94
+
95
+ # Connect example selector to text input
96
+ example_selector.change(
97
+ update_example,
98
+ inputs=[example_selector],
99
+ outputs=[text_input]
100
+ )
101
+
102
+ analyze_button = gr.Button("Compare Both NER Models")
103
+
104
+ # Create outputs for both models
105
+ with gr.Row():
106
+ outputs = []
107
+ for model_name in model_names:
108
+ with gr.Column():
109
+ gr.Markdown(f"### Results from {model_name}")
110
+ output = gr.HighlightedText(label=f"NER Result", combine_adjacent=True)
111
+ outputs.append(output)
112
+
113
+ # Model info section
114
+ with gr.Accordion("Model Usage Information", open=False):
115
+ for model_name in model_names:
116
+ with gr.Row():
117
+ with gr.Column():
118
+ gr.Markdown(f"### {model_name}")
119
+ gr.Code(
120
+ model_info[model_name]["usage"],
121
+ language="python",
122
+ )
123
+ gr.Markdown(f'[Open model page for {model_name}]({model_info[model_name]["link"]})')
124
+
125
+ # Set up the button to analyze with both models
126
+ analyze_button.click(
127
+ analyze_text_with_both_models,
128
+ inputs=[text_input],
129
+ outputs=outputs
130
+ )
131
+
132
+ demo.launch()