nicolasmarques commited on
Commit
99668c4
·
verified ·
1 Parent(s): 479c804

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -97
app.py CHANGED
@@ -1,105 +1,84 @@
1
- # app.py
2
- import re
3
- from langdetect import detect, DetectorFactory
4
- from transformers import pipeline
5
  import gradio as gr
 
 
 
6
 
7
- # tornar detecção determinística
8
- DetectorFactory.seed = 0
9
 
10
- # Pipeline principal de geração multimodal/multilíngue
11
- generator = pipeline(
12
- "text-generation",
13
- model="bigscience/bloom-560m",
14
- device_map="auto" # usa GPU se disponível
15
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- # Mapeamento de ações a palavras-chave em vários idiomas
18
- ACTIONS = {
19
- "expand": {"en": ["expand", "detail", "add"], "pt": ["expanda", "expandir", "detalhe"], "fr": ["développer"]},
20
- "summarize":{"en": ["summarize", "summarise", "summary"], "pt": ["resuma", "resumir", "resumo"], "fr": ["résumer"]},
21
- "simplify": {"en": ["simplify"], "pt": ["simplifique", "simplificar"], "fr": ["simplifier"]},
22
- "continue": {"en": ["continue", "cont"], "pt": ["continue", "continuar"], "fr": ["continuer"]},
23
- }
24
-
25
- # Frases de instrução por idioma
26
- INSTRUCTION = {
27
- "expand": {
28
- "en": "Please expand and detail the following text:",
29
- "pt": "Por favor, expanda e detalhe o texto a seguir:",
30
- "fr": "Veuillez développer et détailler le texte suivant :"
31
- },
32
- "summarize": {
33
- "en": "Please provide a concise summary of the following text:",
34
- "pt": "Por favor, forneça um resumo conciso do texto a seguir:",
35
- "fr": "Veuillez fournir un résumé concis du texte suivant :"
36
- },
37
- "simplify": {
38
- "en": "Please simplify the following text:",
39
- "pt": "Por favor, simplifique o texto a seguir:",
40
- "fr": "Veuillez simplifier le texte suivant :"
41
- },
42
- "continue": {
43
- "en": "Please continue writing the following text:",
44
- "pt": "Por favor, continue o texto a seguir:",
45
- "fr": "Veuillez continuer le texte suivant :"
46
- },
47
- }
48
-
49
- # Frase de humanização por idioma
50
- HUMANIZE = {
51
- "en": "Please make the following text more natural and human-like:",
52
- "pt": "Por favor, torne o texto a seguir mais natural e humano:",
53
- "fr": "Veuillez rendre le texte suivant plus naturel et humain :"
54
- }
55
-
56
- def detect_language(text):
57
  try:
58
- code = detect(text)
 
59
  except:
60
- code = "en"
61
- return code if code in ["en", "pt", "fr"] else "en"
62
-
63
- def detect_action(text, lang):
64
- txt = text.lower()
65
- for action, kwmap in ACTIONS.items():
66
- for kw in kwmap.get(lang, []):
67
- if re.search(rf"\b{kw}\b", txt):
68
- return action
69
- return "continue"
70
-
71
- def clean_text(text, lang):
72
- # Remove as palavras-chave de comando para não poluir o prompt
73
- txt = text
74
- for kw in sum(ACTIONS.values(), []):
75
- txt = re.sub(rf"\b{kw}\b", "", txt, flags=re.IGNORECASE)
76
- return txt.strip()
77
-
78
- def gerar(texto):
79
- # 1. Detecta idioma e ação
80
- lang = detect_language(texto)
81
- action = detect_action(texto, lang)
82
- # 2. Limpa o texto
83
- core = clean_text(texto, lang)
84
- # 3. Gera segundo instrução apropriada
85
- prompt1 = f"{INSTRUCTION[action][lang]}\n\n{core}\n\n"
86
- out1 = generator(prompt1, max_new_tokens=200, temperature=0.7, top_p=0.9)[0]["generated_text"]
87
- # Retira o prompt do início
88
- result1 = out1.replace(prompt1, "").strip()
89
- # 4. Humaniza o texto
90
- prompt2 = f"{HUMANIZE[lang]}\n\n{result1}\n\n"
91
- out2 = generator(prompt2, max_new_tokens=100, temperature=0.6, top_p=0.8)[0]["generated_text"]
92
- result2 = out2.replace(prompt2, "").strip()
93
- return result2
94
-
95
- # Interface Gradio
96
- app = gr.Interface(
97
- fn=gerar,
98
- inputs=gr.Textbox(lines=6, placeholder="Digite seu texto e o comando embutido (ex: 'Por favor, resuma isto')...", label="Entrada"),
99
- outputs=gr.Textbox(label="Resposta IA (mesmo idioma)"),
100
- title="GPT Multilingue Sr. Nicolas",
101
- description="Digite um texto com naturalidade (em pt/en/fr). A IA detecta idioma, executa comando embutido (resuma, expanda, simplifique, continue) e devolve texto humanizado.",
102
- allow_flagging="never"
103
  )
104
 
105
- app.launch()
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
+ from langdetect import detect
4
+ import re
5
 
6
+ # Cria pipeline com modelo leve e rápido
7
+ generator = pipeline("text-generation", model="gpt2", device=-1)
8
 
9
+ def identificar_comando(mensagem):
10
+ comandos = {
11
+ "resumo": ["resuma", "resumir", "resume", "faça um resumo", "resumidamente"],
12
+ "reescrever": ["reescreva", "reescrever", "reescreve", "reformule", "reformulação", "escreva de outro jeito"],
13
+ "expandir": ["aumente", "expanda", "detalhe mais", "escreva mais", "aprofundar", "explique melhor"],
14
+ "corrigir": ["corrija", "melhore", "revise", "melhora", "ajuste", "correção"]
15
+ }
16
+ for tipo, palavras in comandos.items():
17
+ for palavra in palavras:
18
+ if palavra.lower() in mensagem.lower():
19
+ return tipo
20
+ return "gerar"
21
+
22
+ def processar_texto(texto):
23
+ idioma = detectar_idioma(texto)
24
+ comando = identificar_comando(texto)
25
+
26
+ texto_limpo = limpar_texto(texto)
27
+
28
+ if comando == "resumo":
29
+ prompt = f"Resuma o texto a seguir:\n{texto_limpo}\nResumo:"
30
+ elif comando == "reescrever":
31
+ prompt = f"Reescreva este texto com melhor estilo e clareza:\n{texto_limpo}\nNovo texto:"
32
+ elif comando == "expandir":
33
+ prompt = f"Expanda o seguinte texto, adicionando detalhes e explicações:\n{texto_limpo}\nTexto expandido:"
34
+ elif comando == "corrigir":
35
+ prompt = f"Corrija a gramática, ortografia e melhore o estilo deste texto:\n{texto_limpo}\nTexto corrigido:"
36
+ else:
37
+ prompt = f"{texto_limpo}"
38
+
39
+ saida = generator(prompt, max_new_tokens=250, temperature=0.7)[0]['generated_text']
40
+ resposta = saida.replace(prompt, "").strip()
41
 
42
+ # Se ainda tiver o texto antigo, limpa ele
43
+ resposta = resposta.replace(texto_limpo.strip(), "").strip()
44
+
45
+ # Traduz de volta, se necessário
46
+ if idioma == "pt":
47
+ return resposta
48
+ elif idioma == "en":
49
+ return resposta
50
+ else:
51
+ return f"(Resposta gerada em inglês por padrão)\n\n{resposta}"
52
+
53
+ def detectar_idioma(texto):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  try:
55
+ lang = detect(texto)
56
+ return lang
57
  except:
58
+ return "en"
59
+
60
+ def limpar_texto(texto):
61
+ texto = re.sub(r"\s+", " ", texto)
62
+ return texto.strip()
63
+
64
+ title = "🧠 GPT2 App Nicolas"
65
+ description = """
66
+ 🔹 Digite seu texto com instruções no próprio campo: exemplo "resuma isso", "melhore", "reescreva", "expanda".
67
+
68
+ 🔹 A IA detecta automaticamente o que você quer, analisa a linguagem e responde de forma **humanizada**.
69
+
70
+ 🔹 Desenvolvido por **Sr. Nicolas** usando Gradio + Hugging Face.
71
+
72
+ 🔸 Suporte aos idiomas: português, inglês, espanhol, francês (detecção automática).
73
+ """
74
+
75
+ interface = gr.Interface(
76
+ fn=processar_texto,
77
+ inputs=gr.Textbox(lines=10, placeholder="Digite seu texto aqui..."),
78
+ outputs=gr.Textbox(lines=10),
79
+ title=title,
80
+ description=description,
81
+ theme="default",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  )
83
 
84
+ interface.launch()