AshenClock commited on
Commit
fb556ab
·
verified ·
1 Parent(s): a304c58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -24
app.py CHANGED
@@ -203,10 +203,11 @@ FINE ONTOLOGIA.
203
 
204
  def classify_and_translate(question_text: str, model_answer_text: str):
205
  """
206
- Classifica la lingua della domanda e della risposta, quindi traduce la risposta
207
- se la lingua è diversa da quella della domanda. L'idea è di restituire una
208
- risposta nella stessa lingua dell'utente.
209
  """
 
210
  def _extract_label(res):
211
  # Compat: [ {label,score} ] | [ [ {label,score}, ... ] ] | oggetti con .label
212
  try:
@@ -219,51 +220,74 @@ def classify_and_translate(question_text: str, model_answer_text: str):
219
  except Exception:
220
  return None
221
 
222
- # Rilevamento lingua domanda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  try:
224
- question_lang_result = lang_detect_client.text_classification(question_text) # posizionale
225
- question_lang = _extract_label(question_lang_result)
226
- logger.info(f"[LangDetect] Lingua della domanda: {question_lang}")
227
  except Exception:
228
  logger.exception("Errore nel rilevamento della lingua della domanda")
229
  question_lang = None # fallback prudente
230
 
231
- # Rilevamento lingua risposta
232
  try:
233
- answer_lang_result = lang_detect_client.text_classification(model_answer_text) # posizionale
234
- answer_lang = _extract_label(answer_lang_result)
235
- logger.info(f"[LangDetect] Lingua della risposta: {answer_lang}")
236
  except Exception:
237
  logger.exception("Errore nel rilevamento della lingua della risposta")
238
  answer_lang = None # fallback prudente
239
 
240
- # Se detection fallisce o le lingue coincidono: non tradurre
241
  if not question_lang or not answer_lang or question_lang == answer_lang:
242
  logger.info("[Translate] Niente traduzione (lingue uguali o detection fallita).")
243
  return model_answer_text
244
 
245
- # Traduzione (provider esplicito)
246
  translator_model = f"{TRANSLATOR_MODEL_PREFIX}-{answer_lang}-{question_lang}"
247
- translator_client = InferenceClient(
248
  token=HF_API_KEY,
249
  model=translator_model,
250
  provider="hf-inference",
251
  )
252
  try:
253
- translation_result = translator_client.translation(model_answer_text) # posizionale
254
- if isinstance(translation_result, dict):
255
- translated_answer = translation_result.get("translation_text") or model_answer_text
256
- elif hasattr(translation_result, "translation_text"):
257
- translated_answer = translation_result.translation_text or model_answer_text
258
- elif isinstance(translation_result, str):
259
- translated_answer = translation_result
260
  else:
261
- translated_answer = model_answer_text
262
  except Exception:
263
  logger.exception(f"Errore nella traduzione {answer_lang} -> {question_lang}")
264
- translated_answer = model_answer_text
 
 
265
 
266
- return translated_answer
267
 
268
 
269
 
 
203
 
204
  def classify_and_translate(question_text: str, model_answer_text: str):
205
  """
206
+ Classifica la lingua della domanda e della risposta, poi traduce la risposta
207
+ solo se la lingua della risposta è diversa da quella della domanda.
208
+ Tutta la logica (helper, provider check, fallback) è contenuta qui dentro.
209
  """
210
+ # --- Helper interni -----------------------------------------------------
211
  def _extract_label(res):
212
  # Compat: [ {label,score} ] | [ [ {label,score}, ... ] ] | oggetti con .label
213
  try:
 
220
  except Exception:
221
  return None
222
 
223
+ def _ensure_lang_client():
224
+ """
225
+ Restituisce un client di language detection con provider garantito.
226
+ Usa il globale lang_detect_client se ha il provider, altrimenti ne crea uno locale.
227
+ Richiede che HF_API_KEY e LANG_DETECT_MODEL siano definiti globalmente.
228
+ """
229
+ try:
230
+ prov = getattr(lang_detect_client, "provider", None)
231
+ if prov:
232
+ return lang_detect_client
233
+ except NameError:
234
+ # lang_detect_client non definito: creo un client locale
235
+ pass
236
+ # Creo un client locale con provider forzato
237
+ local_client = InferenceClient(
238
+ token=HF_API_KEY,
239
+ model=LANG_DETECT_MODEL,
240
+ provider="hf-inference",
241
+ )
242
+ return local_client
243
+
244
+ # --- Rilevamento lingua -------------------------------------------------
245
+ ld_client = _ensure_lang_client()
246
+
247
  try:
248
+ q_res = ld_client.text_classification(question_text) # argomento posizionale
249
+ question_lang = _extract_label(q_res)
250
+ logger.info(f"[LangDetect] Domanda: {question_lang}")
251
  except Exception:
252
  logger.exception("Errore nel rilevamento della lingua della domanda")
253
  question_lang = None # fallback prudente
254
 
 
255
  try:
256
+ a_res = ld_client.text_classification(model_answer_text) # argomento posizionale
257
+ answer_lang = _extract_label(a_res)
258
+ logger.info(f"[LangDetect] Risposta: {answer_lang}")
259
  except Exception:
260
  logger.exception("Errore nel rilevamento della lingua della risposta")
261
  answer_lang = None # fallback prudente
262
 
263
+ # --- Policy di traduzione (fallback prudente) ---------------------------
264
  if not question_lang or not answer_lang or question_lang == answer_lang:
265
  logger.info("[Translate] Niente traduzione (lingue uguali o detection fallita).")
266
  return model_answer_text
267
 
268
+ # --- Traduzione ---------------------------------------------------------
269
  translator_model = f"{TRANSLATOR_MODEL_PREFIX}-{answer_lang}-{question_lang}"
270
+ tr_client = InferenceClient(
271
  token=HF_API_KEY,
272
  model=translator_model,
273
  provider="hf-inference",
274
  )
275
  try:
276
+ t_res = tr_client.translation(model_answer_text) # argomento posizionale
277
+ if isinstance(t_res, dict):
278
+ translated = t_res.get("translation_text") or model_answer_text
279
+ elif hasattr(t_res, "translation_text"):
280
+ translated = getattr(t_res, "translation_text") or model_answer_text
281
+ elif isinstance(t_res, str):
282
+ translated = t_res
283
  else:
284
+ translated = model_answer_text
285
  except Exception:
286
  logger.exception(f"Errore nella traduzione {answer_lang} -> {question_lang}")
287
+ translated = model_answer_text
288
+
289
+ return translated
290
 
 
291
 
292
 
293