Spaces:
Runtime error
Runtime error
import re | |
from langdetect import detect, DetectorFactory | |
from transformers import pipeline | |
import gradio as gr | |
# Para resultados determinísticos na detecção de idioma | |
DetectorFactory.seed = 0 | |
# Pipeline de geração de texto instruído (text2text) com FLAN-T5 | |
generator = pipeline( | |
"text2text-generation", | |
model="google/flan-t5-small", | |
device=-1 | |
) | |
# Palavras-chave de comando em pt/en/fr | |
COMMANDS = { | |
"resumo": ["resuma", "resumo", "resumir", "summarize", "résumé", "résumer"], | |
"reescrever":["reescreva", "reformule", "reformular", "rewrite", "réécrire"], | |
"expandir": ["expanda", "expansão", "expandir", "detalhe", "expand", "développez"], | |
"corrigir": ["corrija", "corrigir", "melhore", "revise", "correct", "corriger"] | |
} | |
# Mensagens de instrução por comando e idioma | |
INSTRUCTIONS = { | |
"resumo": { | |
"pt": "Resuma o texto a seguir de forma concisa:", | |
"en": "Please summarize the following text concisely:", | |
"fr": "Veuillez résumer le texte suivant de manière concise :" | |
}, | |
"reescrever": { | |
"pt": "Reescreva este texto com mais clareza e estilo:", | |
"en": "Rewrite this text with more clarity and style:", | |
"fr": "Réécrivez ce texte avec plus de clarté et de style :" | |
}, | |
"expandir": { | |
"pt": "Expanda este texto, adicionando detalhes e explicações:", | |
"en": "Expand the following text by adding details and explanations:", | |
"fr": "Développez ce texte en ajoutant des détails et des explications :" | |
}, | |
"corrigir": { | |
"pt": "Corrija gramática, ortografia e estilo deste texto:", | |
"en": "Correct the grammar, spelling, and style of this text:", | |
"fr": "Corrigez la grammaire, l'orthographe et le style de ce texte :" | |
}, | |
} | |
# Prompt de humanização por idioma | |
HUMANIZE = { | |
"pt": "Por favor, torne o texto a seguir mais natural e humano:", | |
"en": "Please make the following text more natural and human-like:", | |
"fr": "Veuillez rendre le texte suivant plus naturel et humain :" | |
} | |
def detect_language(text: str) -> str: | |
try: | |
code = detect(text) | |
return code if code in HUMANIZE else "pt" | |
except: | |
return "pt" | |
def find_command(text: str) -> str: | |
low = text.lower() | |
for cmd, kws in COMMANDS.items(): | |
for kw in kws: | |
if kw in low: | |
return cmd | |
return "expandir" # padrão se não achar comando | |
def clean_text(text: str) -> str: | |
txt = re.sub(r"\s+", " ", text).strip() | |
for kws in COMMANDS.values(): | |
for kw in kws: | |
txt = re.sub(rf"\b{kw}\b", "", txt, flags=re.IGNORECASE) | |
return txt.strip() | |
def gerar_resposta(texto: str) -> str: | |
lang = detect_language(texto) | |
cmd = find_command(texto) | |
core = clean_text(texto) | |
# 1) Geração principal via FLAN-T5 | |
instr = INSTRUCTIONS[cmd][lang] | |
prompt1 = f"{instr}\n\n{core}" | |
out1 = generator(prompt1, max_length=512, do_sample=False)[0]["generated_text"].strip() | |
# 2) Humanização | |
prompt2 = f"{HUMANIZE[lang]}\n\n{out1}" | |
out2 = generator(prompt2, max_length=256, do_sample=False)[0]["generated_text"].strip() | |
return out2 | |
# Interface Gradio | |
app = gr.Interface( | |
fn=gerar_resposta, | |
inputs=gr.Textbox(lines=6, placeholder="Escreva algo com 'resuma', 'expanda', etc...", label="Entrada"), | |
outputs=gr.Textbox(label="Resposta"), | |
title="🧠 IA Instruída Multilíngue", | |
description="Detecta idioma e comando embutido, responde no mesmo idioma e humaniza o texto." | |
) | |
if __name__ == "__main__": | |
app.launch() |