Cicciokr commited on
Commit
82e05bc
·
verified ·
1 Parent(s): 6553df3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import pipeline, AutoModelForMaskedLM, AutoTokenizer
3
+ from cltk.data.fetch import FetchCorpus
4
+ import builtins
5
+ import os
6
+ import json
7
+
8
+ DATA_FILE = "data.json"
9
+
10
+ def load_data():
11
+ """Carica i dati salvati (token e frasi) dal file JSON."""
12
+ if os.path.exists(DATA_FILE):
13
+ with open(DATA_FILE, "r", encoding="utf-8") as f:
14
+ return json.load(f)
15
+ return {"tokens": [], "phrases": {}}
16
+
17
+ def save_data(data):
18
+ """Salva i dati (token e frasi) nel file JSON."""
19
+ with open(DATA_FILE, "w", encoding="utf-8") as f:
20
+ json.dump(data, f, indent=4)
21
+
22
+ data = load_data()
23
+
24
+ def save_token_and_phrase(token, phrase):
25
+ if phrase not in data["phrases"]:
26
+ data["phrases"][phrase] = token
27
+ save_data(data)
28
+
29
+ def get_valid_predictions(sentence, max_attempts=3, top_k=5):
30
+ """Verifica se la frase è già salvata e usa il token corrispondente."""
31
+ if sentence in data["phrases"]:
32
+ return [{"token_str": data["phrases"][sentence], "score": 1.0, "sequence": sentence.replace("[MASK]", data["phrases"][sentence])}]
33
+
34
+ attempt = 0
35
+ filtered_predictions = []
36
+ while attempt < max_attempts:
37
+ predictions = fill_mask_roberta(sentence, top_k=top_k)
38
+ filtered_predictions = [
39
+ pred for pred in predictions if pred["token_str"] not in punctuation_marks
40
+ ]
41
+ if filtered_predictions:
42
+ break
43
+ attempt += 1
44
+ return filtered_predictions
45
+
46
+ # UI per l'inserimento del token e delle frasi
47
+ st.sidebar.header("Gestione Token e Frasi")
48
+ token_input = st.sidebar.text_input("Inserisci il token:")
49
+ phrase_input = st.sidebar.text_area("Inserisci la frase:")
50
+ if st.sidebar.button("Salva Token e Frase"):
51
+ if token_input and phrase_input:
52
+ save_token_and_phrase(token_input, phrase_input)
53
+ st.sidebar.success("Token e frase salvati con successo!")
54
+ else:
55
+ st.sidebar.warning("Inserisci sia un token che una frase validi.")
56
+
57
+ existing_phrases = data.get("phrases", {})
58
+ st.sidebar.subheader("Frasi salvate:")
59
+ st.sidebar.write("\n".join(existing_phrases.keys()) if existing_phrases else "Nessuna frase salvata.")
60
+
61
+ _original_input = builtins.input
62
+ def _always_yes(prompt=""):
63
+ print(prompt, "Y") # per far vedere a log che abbiamo risposto 'Y'
64
+ return "Y"
65
+
66
+ builtins.input = _always_yes
67
+
68
+ corpus_downloader = FetchCorpus(language="lat")
69
+ corpus_downloader.import_corpus("lat_models_cltk")
70
+
71
+ try:
72
+ from cltk import NLP
73
+ nlp_lat = NLP(language="lat")
74
+ except ImportError:
75
+ nlp_lat = None
76
+
77
+ if "input_text_value" not in st.session_state:
78
+ st.session_state["input_text_value"] = "Lorem ipsum dolor sit amet, [MASK] adipiscing elit."
79
+
80
+ tokenizer_roberta = AutoTokenizer.from_pretrained("Cicciokr/Roberta-Base-Latin-Uncased")
81
+ model_roberta = AutoModelForMaskedLM.from_pretrained("Cicciokr/Roberta-Base-Latin-Uncased")
82
+ fill_mask_roberta = pipeline("fill-mask", model=model_roberta, tokenizer=tokenizer_roberta)
83
+
84
+ punctuation_marks = {".", ",", ";", ":", "!", "?"}
85
+
86
+ input_text = st.text_area(
87
+ label="Testo:",
88
+ height=150,
89
+ key="input_text_value"
90
+ )
91
+
92
+ if input_text:
93
+ input_text_roberta = input_text.replace("[MASK]", "<mask>")
94
+ predictions_roberta = get_valid_predictions(input_text_roberta)
95
+ st.subheader("Risultati delle previsioni:")
96
+ for pred in predictions_roberta:
97
+ st.write(f" Token: {pred['token_str']}")
98
+ st.write(f" Probabilità: {pred['score']:.4f}")
99
+ st.write(f" Sequence: {pred['sequence']}")
100
+ st.write("---")
101
+ if nlp_lat is not None:
102
+ st.subheader("Analisi Morfologica con CLTK")
103
+ for pred in predictions_roberta:
104
+ doc = nlp_lat(pred['token_str'])
105
+ st.write(f"Frase: {pred['token_str']}")
106
+ for w in doc.words:
107
+ st.write(
108
+ f"- **Token**: {w.string}\n"
109
+ f" - Lemma: {w.lemma}\n"
110
+ f" - UPOS: {w.upos}\n"
111
+ f" - Morph: {w.features}\n"
112
+ )
113
+ st.write("---")
114
+ else:
115
+ st.warning("CLTK non installato. Esegui 'pip install cltk' per abilitare l'analisi.")