nicolasmarques commited on
Commit
7cc7b40
·
verified ·
1 Parent(s): fbd2fbc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -67
app.py CHANGED
@@ -1,105 +1,80 @@
1
  import re
2
  from langdetect import detect, DetectorFactory
3
- from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
4
  import gradio as gr
5
 
6
- # Define aleatoriedade fixa para a detecção de idioma
7
  DetectorFactory.seed = 0
8
 
9
- # Modelo T5 em português da Unicamp (compatível com Hugging Face)
10
- model_name = "unicamp-dl/ptt5-base-portuguese-vocab"
11
-
12
- # Força uso do tokenizer "slow", que evita erro de conversão
13
- tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False)
14
- model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
15
-
16
- # Pipeline principal
17
- generator = pipeline("text2text-generation", model=model, tokenizer=tokenizer, device=-1)
18
 
19
- # Comandos reconhecidos
20
  COMMANDS = {
21
- "resumo": ["resuma", "resumo", "resumir"],
22
  "reescrever": ["reescreva", "reformule", "reformular"],
23
  "expandir": ["expanda", "expansão", "expandir", "detalhe"],
24
  "corrigir": ["corrija", "corrigir", "melhore", "revise"]
25
  }
26
 
27
- # Prompts humanizadores
28
- HUMANIZE_PROMPT = {
29
- "pt": "Por favor, torne o texto a seguir mais natural e humano:\n\n",
30
- "en": "Please make the following text more natural and human-like:\n\n",
31
- "fr": "Veuillez rendre le texte suivant plus naturel et humain :\n\n"
 
32
  }
33
 
34
- def detect_language(text: str) -> str:
35
  try:
36
  lang = detect(text)
37
- return lang if lang in HUMANIZE_PROMPT else "pt"
38
  except:
39
  return "pt"
40
 
41
- def find_command(text: str, lang: str) -> str:
42
- low = text.lower()
43
- for cmd, kws in COMMANDS.items():
44
- for kw in kws:
45
- if kw in low:
46
  return cmd
47
  return "gerar"
48
 
49
- def clean_text(text: str) -> str:
50
- txt = re.sub(r"\s+", " ", text)
51
- for kws in COMMANDS.values():
52
- for kw in kws:
53
- txt = re.sub(rf"\b{kw}\b", "", txt, flags=re.IGNORECASE)
54
- return txt.strip()
55
 
56
- def build_prompt(core: str, cmd: str, lang: str) -> str:
57
- if cmd == "resumo":
58
- head = {
59
- "pt": "Resuma o texto a seguir de forma concisa:\n\n",
60
- "en": "Summarize the following text concisely:\n\n",
61
- "fr": "Résumez le texte suivant de manière concise :\n\n"
62
- }
63
- elif cmd == "reescrever":
64
- head = {
65
- "pt": "Reescreva este texto com mais clareza e estilo:\n\n",
66
- "en": "Rewrite this text with more clarity and style:\n\n",
67
- "fr": "Réécrivez ce texte avec plus de clarté et de style :\n\n"
68
- }
69
- elif cmd == "expandir":
70
- head = {
71
- "pt": "Expanda este texto, adicionando detalhes e explicações:\n\n",
72
- "en": "Expand this text, adding details and explanations:\n\n",
73
- "fr": "Développez ce texte en ajoutant des détails et des explications :\n\n"
74
- }
75
- elif cmd == "corrigir":
76
- head = {
77
- "pt": "Corrija gramática, ortografia e estilo deste texto:\n\n",
78
- "en": "Correct the grammar, spelling, and style of this text:\n\n",
79
- "fr": "Corrigez la grammaire, l'orthographe et le style de ce texte :\n\n"
80
- }
81
- else:
82
- head = {"pt": "", "en": "", "fr": ""}
83
- return head[lang] + core + "\n\n"
84
 
85
- def gerar_resposta(texto: str) -> str:
86
  lang = detect_language(texto)
87
- cmd = find_command(texto, lang)
88
  core = clean_text(texto)
 
89
 
90
- prompt = build_prompt(core, cmd, lang)
91
  output = generator(prompt, max_new_tokens=256, temperature=0.7, top_p=0.9)[0]["generated_text"]
92
  resposta = output.replace(prompt, "").strip()
93
 
94
- return resposta
 
 
 
95
 
96
- # Interface Gradio
97
  demo = gr.Interface(
98
  fn=gerar_resposta,
99
- inputs=gr.Textbox(lines=6, placeholder="Digite um texto com: resuma, expanda, corrija...", label="Entrada"),
100
  outputs=gr.Textbox(label="Resposta da IA"),
101
- title="🧠 IA Multilingue do Sr. Nicolas",
102
- description="Detecta idioma e comando embutido. Usa modelo PTT5 treinado em português.",
103
  allow_flagging="never"
104
  )
105
 
 
1
  import re
2
  from langdetect import detect, DetectorFactory
3
+ from transformers import pipeline
4
  import gradio as gr
5
 
6
+ # Garante consistência nos resultados do langdetect
7
  DetectorFactory.seed = 0
8
 
9
+ # Carrega modelo de texto em português
10
+ generator = pipeline(
11
+ "text2text-generation",
12
+ model="unicamp-dl/ptt5-base-portuguese-vocab",
13
+ tokenizer="unicamp-dl/ptt5-base-portuguese-vocab"
14
+ )
 
 
 
15
 
16
+ # Mapeamento de comandos (em português)
17
  COMMANDS = {
18
+ "resumo": ["resuma", "resumo", "resumir"],
19
  "reescrever": ["reescreva", "reformule", "reformular"],
20
  "expandir": ["expanda", "expansão", "expandir", "detalhe"],
21
  "corrigir": ["corrija", "corrigir", "melhore", "revise"]
22
  }
23
 
24
+ PROMPTS = {
25
+ "resumo": "Resuma o texto a seguir:\n\n",
26
+ "reescrever": "Reescreva com mais clareza e estilo:\n\n",
27
+ "expandir": "Expanda este texto, adicionando detalhes e explicações:\n\n",
28
+ "corrigir": "Corrija a gramática, ortografia e estilo do seguinte texto:\n\n",
29
+ "gerar": ""
30
  }
31
 
32
+ def detect_language(text):
33
  try:
34
  lang = detect(text)
35
+ return lang if lang in ["pt", "en", "fr"] else "pt"
36
  except:
37
  return "pt"
38
 
39
+ def find_command(text, lang):
40
+ text_lower = text.lower()
41
+ for cmd, keywords in COMMANDS.items():
42
+ for kw in keywords:
43
+ if kw in text_lower:
44
  return cmd
45
  return "gerar"
46
 
47
+ def clean_text(text):
48
+ text = re.sub(r"\s+", " ", text).strip()
49
+ for keywords in COMMANDS.values():
50
+ for kw in keywords:
51
+ text = re.sub(rf"\b{kw}\b", "", text, flags=re.IGNORECASE)
52
+ return text.strip(": ").strip()
53
 
54
+ def build_prompt(core, cmd):
55
+ return PROMPTS.get(cmd, "") + core
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ def gerar_resposta(texto):
58
  lang = detect_language(texto)
59
+ cmd = find_command(texto, lang)
60
  core = clean_text(texto)
61
+ prompt = build_prompt(core, cmd)
62
 
 
63
  output = generator(prompt, max_new_tokens=256, temperature=0.7, top_p=0.9)[0]["generated_text"]
64
  resposta = output.replace(prompt, "").strip()
65
 
66
+ if resposta.lower().startswith(core.lower()):
67
+ resposta = resposta[len(core):].strip()
68
+
69
+ return resposta or "⚠️ A IA não conseguiu processar esse texto. Tente reformular."
70
 
71
+ # Interface
72
  demo = gr.Interface(
73
  fn=gerar_resposta,
74
+ inputs=gr.Textbox(lines=6, placeholder="Digite algo como: Corrija: O menino está brincano...", label="Entrada"),
75
  outputs=gr.Textbox(label="Resposta da IA"),
76
+ title="🧠 IA Multilingue Sr. Nicolas",
77
+ description="Detecta comando embutido e devolve resposta humanizada em português.",
78
  allow_flagging="never"
79
  )
80