devusman commited on
Commit
5a3f6ab
·
1 Parent(s): e90e953

all in italian

Browse files
Files changed (1) hide show
  1. app.py +42 -14
app.py CHANGED
@@ -17,12 +17,9 @@ except OSError:
17
 
18
  # Inizializza l'app Flask
19
  app = Flask(__name__)
20
-
21
- # Abilita la Condivisione delle Risorse tra Origini Diverse (CORS)
22
  CORS(app)
23
 
24
  # --- INIZIO SEZIONE TRADUZIONI ---
25
- # Mappe per le traduzioni in italiano delle spiegazioni di spaCy
26
  SPIEGAZIONI_POS_IT = {
27
  "ADJ": "Aggettivo", "ADP": "Preposizione", "ADV": "Avverbio", "AUX": "Ausiliare",
28
  "CONJ": "Congiunzione", "CCONJ": "Congiunzione Coordinante", "SCONJ": "Congiunzione Subordinante",
@@ -38,17 +35,54 @@ SPIEGAZIONI_ENT_IT = {
38
  "MISC": "Miscellanea: Entità che non rientrano nelle altre categorie (es. eventi, nazionalità, prodotti)."
39
  }
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  def spiega_in_italiano(tag, tipo='pos'):
42
  """Fornisce una spiegazione in italiano per un tag POS o di entità."""
43
  if tipo == 'pos':
44
  return SPIEGAZIONI_POS_IT.get(tag, tag)
45
  if tipo == 'ent':
46
  return SPIEGAZIONI_ENT_IT.get(tag, tag)
47
- # Ritorna il tag originale se non trova una spiegazione
48
  return tag
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  # --- FINE SEZIONE TRADUZIONI ---
50
 
51
- # Mappatura delle etichette di dipendenza di spaCy alle nostre etichette di analisi logica con spiegazioni
52
  MAPPA_DEP = {
53
  "nsubj": {"label": "Soggetto", "description": "Indica chi o cosa compie l'azione o si trova in un certo stato."},
54
  "ROOT": {"label": "Predicato Verbale", "description": "Esprime l'azione o lo stato del soggetto."},
@@ -66,7 +100,6 @@ MAPPA_DEP = {
66
  }
67
 
68
  def ottieni_tipo_complemento_con_dettagli(token):
69
- """Affina il tipo di complemento basandosi sulla preposizione precedente e fornisce dettagli."""
70
  preposizione = ""
71
  for figlio in token.children:
72
  if figlio.dep_ == "case":
@@ -100,13 +133,11 @@ def ottieni_tipo_complemento_con_dettagli(token):
100
  return {"label": "Complemento Indiretto", "description": "Fornisce un'informazione generica non classificata in modo più specifico."}
101
 
102
  def ottieni_testo_completo(token):
103
- """Costruisce ricorsivamente il testo completo di un sintagma, partendo da un token principale."""
104
  token_sintagma = [token] + sorted([t for t in token.children if t.dep_ in ('det', 'amod', 'case', 'advmod')], key=lambda x: x.i)
105
  token_sintagma.sort(key=lambda x: x.i)
106
  return " ".join(t.text for t in token_sintagma)
107
 
108
  def costruisci_sintagmi_con_dettagli(lista_token):
109
- """Aggrega i token in sintagmi grammaticali significativi con spiegazioni dettagliate."""
110
  mappa_sintagmi = {}
111
 
112
  for token in lista_token:
@@ -116,8 +147,8 @@ def costruisci_sintagmi_con_dettagli(lista_token):
116
  "token_details": {
117
  "lemma": token.lemma_,
118
  "pos": f"{token.pos_}: {spiega_in_italiano(token.pos_, 'pos')}",
119
- "tag": f"{token.tag_}: {spiega_in_italiano(token.tag_, 'pos')}", # Usa 'pos' per la spiegazione del tag più generica
120
- "morph": str(token.morph) if token.morph else "Non disponibile"
121
  },
122
  "label_info": {},
123
  "token": token
@@ -146,7 +177,7 @@ def costruisci_sintagmi_con_dettagli(lista_token):
146
  "lemma": copula.lemma_,
147
  "pos": f"{copula.pos_}: {spiega_in_italiano(copula.pos_, 'pos')}",
148
  "tag": f"{copula.tag_}: {spiega_in_italiano(copula.tag_, 'pos')}",
149
- "morph": str(copula.morph) if copula.morph else "Non disponibile"
150
  }
151
  })
152
  risultato_analisi.append({
@@ -175,18 +206,15 @@ def costruisci_sintagmi_con_dettagli(lista_token):
175
  return risultato_analisi
176
 
177
  def analizza_proposizione_con_dettagli(token_proposizione):
178
- """Analizza una singola proposizione (principale o subordinata) con dettagli."""
179
  token_nella_proposizione = [t for t in token_proposizione if t.dep_ != 'mark']
180
  return costruisci_sintagmi_con_dettagli(token_nella_proposizione)
181
 
182
  @app.route("/")
183
  def home():
184
- """Restituisce un semplice messaggio di benvenuto per la radice dell'API."""
185
  return jsonify({"messaggio": "L'API per l'analisi logica è in esecuzione. Usa l'endpoint /api/analyze."})
186
 
187
  @app.route('/api/analyze', methods=['POST'])
188
  def analizza_frase():
189
- """Endpoint principale per ricevere una frase e restituire l'analisi logica completa con dettagli."""
190
  try:
191
  dati = request.get_json()
192
  if not dati or 'sentence' not in dati:
 
17
 
18
  # Inizializza l'app Flask
19
  app = Flask(__name__)
 
 
20
  CORS(app)
21
 
22
  # --- INIZIO SEZIONE TRADUZIONI ---
 
23
  SPIEGAZIONI_POS_IT = {
24
  "ADJ": "Aggettivo", "ADP": "Preposizione", "ADV": "Avverbio", "AUX": "Ausiliare",
25
  "CONJ": "Congiunzione", "CCONJ": "Congiunzione Coordinante", "SCONJ": "Congiunzione Subordinante",
 
35
  "MISC": "Miscellanea: Entità che non rientrano nelle altre categorie (es. eventi, nazionalità, prodotti)."
36
  }
37
 
38
+ # NUOVA SEZIONE: Dizionario per le traduzioni morfologiche
39
+ TRADUZIONI_MORFOLOGIA = {
40
+ # Chiavi
41
+ "Gender": "Genere", "Number": "Numero", "Mood": "Modo", "Tense": "Tempo",
42
+ "Person": "Persona", "VerbForm": "Forma del Verbo", "PronType": "Tipo di Pronome",
43
+ "Clitic": "Clitico", "Definite": "Definitezza", "Degree": "Grado",
44
+ # Valori
45
+ "Masc": "Maschile", "Fem": "Femminile",
46
+ "Sing": "Singolare", "Plur": "Plurale",
47
+ "Ind": "Indicativo", "Sub": "Congiuntivo", "Cnd": "Condizionale", "Imp": "Imperativo", "Inf": "Infinito", "Part": "Participio", "Ger": "Gerundio",
48
+ "Pres": "Presente", "Past": "Passato", "Fut": "Futuro", "Imp": "Imperfetto",
49
+ "1": "1ª", "2": "2ª", "3": "3ª",
50
+ "Fin": "Finita", "Inf": "Infinito", "Part": "Participio", "Ger": "Gerundio",
51
+ "Prs": "Personale", "Rel": "Relativo", "Int": "Interrogativo", "Dem": "Dimostrativo", "Art": "Articolativo",
52
+ "Yes": "Sì",
53
+ "Ind": "Indeterminato", "Def": "Determinato",
54
+ "Abs": "Assoluto", "Cmp": "Comparativo",
55
+ }
56
+
57
  def spiega_in_italiano(tag, tipo='pos'):
58
  """Fornisce una spiegazione in italiano per un tag POS o di entità."""
59
  if tipo == 'pos':
60
  return SPIEGAZIONI_POS_IT.get(tag, tag)
61
  if tipo == 'ent':
62
  return SPIEGAZIONI_ENT_IT.get(tag, tag)
 
63
  return tag
64
+
65
+ def traduci_morfologia(morph_str):
66
+ """Traduce la stringa morfologica in un formato leggibile in italiano."""
67
+ if not morph_str:
68
+ return "Non disponibile"
69
+
70
+ parti = morph_str.split('|')
71
+ parti_tradotte = []
72
+ for parte in parti:
73
+ if '=' in parte:
74
+ chiave, valore = parte.split('=', 1)
75
+ chiave_tradotta = TRADUZIONI_MORFOLOGIA.get(chiave, chiave)
76
+ valore_tradotto = TRADUZIONI_MORFOLOGIA.get(valore, valore)
77
+ parti_tradotte.append(f"{chiave_tradotta}: {valore_tradotto}")
78
+ else:
79
+ # Gestisce i casi in cui non c'è una coppia chiave=valore
80
+ parti_tradotte.append(TRADUZIONI_MORFOLOGIA.get(parte, parte))
81
+
82
+ return ", ".join(parti_tradotte)
83
  # --- FINE SEZIONE TRADUZIONI ---
84
 
85
+
86
  MAPPA_DEP = {
87
  "nsubj": {"label": "Soggetto", "description": "Indica chi o cosa compie l'azione o si trova in un certo stato."},
88
  "ROOT": {"label": "Predicato Verbale", "description": "Esprime l'azione o lo stato del soggetto."},
 
100
  }
101
 
102
  def ottieni_tipo_complemento_con_dettagli(token):
 
103
  preposizione = ""
104
  for figlio in token.children:
105
  if figlio.dep_ == "case":
 
133
  return {"label": "Complemento Indiretto", "description": "Fornisce un'informazione generica non classificata in modo più specifico."}
134
 
135
  def ottieni_testo_completo(token):
 
136
  token_sintagma = [token] + sorted([t for t in token.children if t.dep_ in ('det', 'amod', 'case', 'advmod')], key=lambda x: x.i)
137
  token_sintagma.sort(key=lambda x: x.i)
138
  return " ".join(t.text for t in token_sintagma)
139
 
140
  def costruisci_sintagmi_con_dettagli(lista_token):
 
141
  mappa_sintagmi = {}
142
 
143
  for token in lista_token:
 
147
  "token_details": {
148
  "lemma": token.lemma_,
149
  "pos": f"{token.pos_}: {spiega_in_italiano(token.pos_, 'pos')}",
150
+ "tag": f"{token.tag_}: {spiega_in_italiano(token.tag_, 'pos')}",
151
+ "morph": traduci_morfologia(str(token.morph)) # AGGIORNATO
152
  },
153
  "label_info": {},
154
  "token": token
 
177
  "lemma": copula.lemma_,
178
  "pos": f"{copula.pos_}: {spiega_in_italiano(copula.pos_, 'pos')}",
179
  "tag": f"{copula.tag_}: {spiega_in_italiano(copula.tag_, 'pos')}",
180
+ "morph": traduci_morfologia(str(copula.morph)) # AGGIORNATO
181
  }
182
  })
183
  risultato_analisi.append({
 
206
  return risultato_analisi
207
 
208
  def analizza_proposizione_con_dettagli(token_proposizione):
 
209
  token_nella_proposizione = [t for t in token_proposizione if t.dep_ != 'mark']
210
  return costruisci_sintagmi_con_dettagli(token_nella_proposizione)
211
 
212
  @app.route("/")
213
  def home():
 
214
  return jsonify({"messaggio": "L'API per l'analisi logica è in esecuzione. Usa l'endpoint /api/analyze."})
215
 
216
  @app.route('/api/analyze', methods=['POST'])
217
  def analizza_frase():
 
218
  try:
219
  dati = request.get_json()
220
  if not dati or 'sentence' not in dati: