Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -25,31 +25,38 @@ tokenizer = AutoTokenizer.from_pretrained(MODEL_KEY)
|
|
25 |
model = AutoModelForCausalLM.from_pretrained(MODEL_KEY)
|
26 |
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
27 |
|
28 |
-
#
|
|
|
|
|
|
|
|
|
|
|
29 |
context_map = {
|
30 |
"imdb": "Dom: Cine | Estilo: Opinión",
|
31 |
"daily_dialog": "Dom: Conversación | Estilo: Diálogo diario",
|
32 |
"go_emotions": "Dom: Emociones | Estilo: Clasificación emocional",
|
33 |
"wikitext": "Dom: Enciclopedia | Estilo: Conocimiento general",
|
|
|
|
|
34 |
}
|
35 |
|
36 |
-
#
|
37 |
-
|
38 |
-
|
39 |
-
#
|
40 |
-
|
41 |
-
|
42 |
-
if sample_index >= len(dataset):
|
43 |
-
return "Índice fuera de rango."
|
44 |
-
|
45 |
-
example = dataset[sample_index]
|
46 |
-
text = example.get("text") or example.get("utterance") or example.get("content") or str(example)
|
47 |
|
48 |
-
|
49 |
-
|
50 |
output = generator(prompt, max_length=int(max_length), num_return_sequences=1)[0]["generated_text"]
|
51 |
return output
|
52 |
|
|
|
|
|
|
|
|
|
|
|
53 |
# Traducción
|
54 |
def translate_text(text, lang):
|
55 |
translator = Translator(to_lang=lang)
|
@@ -58,17 +65,40 @@ def translate_text(text, lang):
|
|
58 |
except Exception as e:
|
59 |
return f"Error: {str(e)}"
|
60 |
|
61 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
with gr.Blocks() as demo:
|
63 |
gr.Markdown("# 🧠 MultiDomain Text Generator + Translator")
|
64 |
|
65 |
-
with gr.Tab("Generar
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
btn_generate = gr.Button("Generar texto")
|
71 |
-
btn_generate.click(generate_text, inputs=[dataset_name, sample_index, max_len], outputs=output_text)
|
72 |
|
73 |
with gr.Tab("Traducir texto"):
|
74 |
input_text = gr.Textbox(label="Texto a traducir")
|
@@ -78,4 +108,3 @@ with gr.Blocks() as demo:
|
|
78 |
btn_translate.click(translate_text, inputs=[input_text, lang], outputs=output_translation)
|
79 |
|
80 |
demo.launch()
|
81 |
-
|
|
|
25 |
model = AutoModelForCausalLM.from_pretrained(MODEL_KEY)
|
26 |
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
27 |
|
28 |
+
# Cargar modelos para Preguntas y Respuestas (QA)
|
29 |
+
qa_model = AutoModelForQuestionAnswering.from_pretrained("deepset/roberta-base-squad2")
|
30 |
+
qa_tokenizer = AutoTokenizer.from_pretrained("deepset/roberta-base-squad2")
|
31 |
+
qa_pipeline = pipeline("question-answering", model=qa_model, tokenizer=qa_tokenizer)
|
32 |
+
|
33 |
+
# Agregar más datasets para mejorar las respuestas
|
34 |
context_map = {
|
35 |
"imdb": "Dom: Cine | Estilo: Opinión",
|
36 |
"daily_dialog": "Dom: Conversación | Estilo: Diálogo diario",
|
37 |
"go_emotions": "Dom: Emociones | Estilo: Clasificación emocional",
|
38 |
"wikitext": "Dom: Enciclopedia | Estilo: Conocimiento general",
|
39 |
+
"math": "Dom: Matemáticas | Estilo: Problema matemático", # Agregar problemas de matemáticas
|
40 |
+
"empathetic_dialogues": "Dom: Psicología | Estilo: Apoyo emocional", # Para el comportamiento emocional
|
41 |
}
|
42 |
|
43 |
+
# Detectar idioma automáticamente
|
44 |
+
def detect_language(text):
|
45 |
+
try:
|
46 |
+
return detect(text) # Detecta el idioma de la entrada
|
47 |
+
except:
|
48 |
+
return "en" # Si no se puede detectar, se asume inglés
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
+
# Generación de texto (si se solicita un cuento, por ejemplo)
|
51 |
+
def generate_text(prompt, max_length=100):
|
52 |
output = generator(prompt, max_length=int(max_length), num_return_sequences=1)[0]["generated_text"]
|
53 |
return output
|
54 |
|
55 |
+
# Preguntas y respuestas basadas en contexto
|
56 |
+
def answer_question(question, context):
|
57 |
+
result = qa_pipeline(question=question, context=context)
|
58 |
+
return result['answer']
|
59 |
+
|
60 |
# Traducción
|
61 |
def translate_text(text, lang):
|
62 |
translator = Translator(to_lang=lang)
|
|
|
65 |
except Exception as e:
|
66 |
return f"Error: {str(e)}"
|
67 |
|
68 |
+
# Selección del contexto y modelo según la solicitud
|
69 |
+
def process_input(user_input):
|
70 |
+
# Detectar idioma
|
71 |
+
detected_lang = detect_language(user_input)
|
72 |
+
print(f"Idioma detectado: {detected_lang}")
|
73 |
+
|
74 |
+
# Si la entrada es una pregunta, usaremos un modelo de Preguntas y Respuestas
|
75 |
+
if '?' in user_input:
|
76 |
+
context = "Este es un contexto general. Puedo responder preguntas específicas sobre cine, ciencia, o emociones."
|
77 |
+
answer = answer_question(user_input, context)
|
78 |
+
return answer
|
79 |
+
elif "math" in user_input.lower():
|
80 |
+
# Si se detecta una pregunta matemática
|
81 |
+
return "Resolviendo la operación matemática..."
|
82 |
+
elif "cuento" in user_input.lower():
|
83 |
+
# Si el usuario solicita un cuento
|
84 |
+
prompt = "Había una vez, en un reino lejano..."
|
85 |
+
return generate_text(prompt, max_length=200)
|
86 |
+
elif "emoción" in user_input.lower():
|
87 |
+
# Si es una solicitud de apoyo emocional
|
88 |
+
context = "Dom: Psicología | Estilo: Apoyo emocional. ¿Cómo te sientes hoy?"
|
89 |
+
return generate_text(context + " Estoy aquí para apoyarte", max_length=100)
|
90 |
+
else:
|
91 |
+
return "No entiendo la solicitud, por favor intenta preguntar algo más específico."
|
92 |
+
|
93 |
+
# Interfaz de Gradio
|
94 |
with gr.Blocks() as demo:
|
95 |
gr.Markdown("# 🧠 MultiDomain Text Generator + Translator")
|
96 |
|
97 |
+
with gr.Tab("Generar respuestas y contar historias"):
|
98 |
+
user_input = gr.Textbox(label="Tu pregunta o solicitud", placeholder="Haz una pregunta o pide un cuento...")
|
99 |
+
output_text = gr.Textbox(label="Respuesta generada")
|
100 |
+
btn_generate = gr.Button("Generar respuesta o cuento")
|
101 |
+
btn_generate.click(process_input, inputs=user_input, outputs=output_text)
|
|
|
|
|
102 |
|
103 |
with gr.Tab("Traducir texto"):
|
104 |
input_text = gr.Textbox(label="Texto a traducir")
|
|
|
108 |
btn_translate.click(translate_text, inputs=[input_text, lang], outputs=output_translation)
|
109 |
|
110 |
demo.launch()
|
|