File size: 3,523 Bytes
99668c4
46d8eae
 
 
d38f804
f1e41b5
46d8eae
99668c4
f1e41b5
46d8eae
f1e41b5
 
46d8eae
 
99668c4
f1e41b5
46d8eae
f1e41b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46d8eae
 
f1e41b5
 
 
 
 
46d8eae
 
 
2bc0299
f1e41b5
 
2bc0299
46d8eae
 
8bcd145
46d8eae
 
 
 
 
f1e41b5
99668c4
46d8eae
f1e41b5
46d8eae
 
 
 
 
 
 
8bcd145
46d8eae
 
f1e41b5
 
 
 
46d8eae
f1e41b5
 
 
46d8eae
f1e41b5
46d8eae
f1e41b5
 
46d8eae
f1e41b5
 
 
 
d38f804
 
46d8eae
f1e41b5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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()