Spaces:
Running
Running
import gradio as gr | |
from transformers import pipeline | |
# Model names (keeping it programmatic) | |
model_names = [ | |
r"DeepMount00/Italian_NER_XXL_v2", | |
"DeepMount00/Italian_NER_XXL" | |
] | |
# Example texts | |
example_texts = { | |
"Example 1 - Simple": "Aspetterò Marco per un altro quarto d'ora. Con questo ritardo rischio di prendere una multa di 40 euro.", | |
"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).", | |
"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.", | |
"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.", | |
"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.", | |
"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\".", | |
"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 è [email protected] e il suo numero di telefono è +39 347 1122334." | |
} | |
# Default example for usage examples | |
default_example = example_texts["Example 1 - Simple"] | |
# Programmatically build the model info dict | |
model_info = { | |
model_name: { | |
"link": f"https://huggingface.co/{model_name}", | |
"usage": f"""from transformers import pipeline | |
ner = pipeline("ner", model="{model_name}", grouped_entities=True) | |
result = ner("{default_example}") | |
print(result)""", | |
} | |
for model_name in model_names | |
} | |
# Load models into a dictionary programmatically | |
models = { | |
model_name: pipeline("ner", model=model_name, grouped_entities=True) | |
for model_name in model_names | |
} | |
# Function to run NER on input text with a specific model | |
def analyze_text_with_model(text, model_name): | |
ner = models[model_name] | |
ner_results = ner(text) | |
highlighted_text = [] | |
last_idx = 0 | |
for entity in ner_results: | |
start = entity["start"] | |
end = entity["end"] | |
label = entity["entity_group"] | |
# Add non-entity text | |
if start > last_idx: | |
highlighted_text.append((text[last_idx:start], None)) | |
# Add entity text | |
highlighted_text.append((text[start:end], label)) | |
last_idx = end | |
# Add any remaining text after the last entity | |
if last_idx < len(text): | |
highlighted_text.append((text[last_idx:], None)) | |
return highlighted_text | |
# Run both models and return results | |
def analyze_text_with_both_models(text): | |
results = [] | |
for model_name in model_names: | |
results.append(analyze_text_with_model(text, model_name)) | |
return results | |
# Function to update text input based on example selection | |
def update_example(example_name): | |
return example_texts[example_name] | |
with gr.Blocks() as demo: | |
gr.Markdown("# Named Entity Recognition (NER) Model Comparison") | |
# Example selector | |
example_selector = gr.Radio( | |
choices=list(example_texts.keys()), | |
label="Select Example Text", | |
value="Example 1 - Simple" | |
) | |
# Textbox for input text | |
text_input = gr.Textbox( | |
label="Enter Text", | |
lines=10, # Increased number of lines to better display the longer example | |
value=example_texts["Example 1 - Simple"], | |
) | |
# Connect example selector to text input | |
example_selector.change( | |
update_example, | |
inputs=[example_selector], | |
outputs=[text_input] | |
) | |
analyze_button = gr.Button("Compare Both NER Models") | |
# Create outputs for both models | |
with gr.Row(): | |
outputs = [] | |
for model_name in model_names: | |
with gr.Column(): | |
gr.Markdown(f"### Results from {model_name}") | |
output = gr.HighlightedText(label=f"NER Result", combine_adjacent=True) | |
outputs.append(output) | |
# Model info section | |
with gr.Accordion("Model Usage Information", open=False): | |
for model_name in model_names: | |
with gr.Row(): | |
with gr.Column(): | |
gr.Markdown(f"### {model_name}") | |
gr.Code( | |
model_info[model_name]["usage"], | |
language="python", | |
) | |
gr.Markdown(f'[Open model page for {model_name}]({model_info[model_name]["link"]})') | |
# Set up the button to analyze with both models | |
analyze_button.click( | |
analyze_text_with_both_models, | |
inputs=[text_input], | |
outputs=outputs | |
) | |
demo.launch() |