Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,166 +1,194 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import pipeline
|
3 |
import torch
|
4 |
import warnings
|
5 |
-
import numpy as np
|
6 |
-
from PIL import Image
|
7 |
warnings.filterwarnings('ignore')
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
}
|
24 |
|
25 |
-
def
|
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 |
-
def process_image_caption(image):
|
61 |
-
if image is None:
|
62 |
-
return "Por favor, forneça uma imagem."
|
63 |
-
return models['image_caption'](image)[0]['generated_text']
|
64 |
-
|
65 |
-
def process_tts(text):
|
66 |
-
if not text:
|
67 |
-
return None
|
68 |
-
return models['text_to_speech'](text)
|
69 |
-
|
70 |
-
def process_zero_shot(text, labels):
|
71 |
-
if not text or not labels:
|
72 |
-
return "Por favor, forneça texto e categorias."
|
73 |
-
result = models['zero_shot'](text, labels.split(','))
|
74 |
-
return f"Classificação: {result['labels'][0]} (Confiança: {result['scores'][0]:.2f})"
|
75 |
-
|
76 |
-
def process_ner(text):
|
77 |
-
if not text:
|
78 |
-
return "Por favor, forneça um texto para análise."
|
79 |
-
results = models['ner'](text)
|
80 |
-
entities = []
|
81 |
-
for result in results:
|
82 |
-
entities.append(f"{result['word']}: {result['entity']}")
|
83 |
-
return "\n".join(entities)
|
84 |
-
|
85 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
86 |
-
gr.HTML(
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
-
with gr.
|
89 |
-
#
|
90 |
-
with gr.
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
|
104 |
-
#
|
105 |
-
with gr.
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
text_sent = gr.Textbox(label="Texto")
|
133 |
-
sent_button = gr.Button("Analisar Sentimento")
|
134 |
-
sent_output = gr.Textbox(label="Resultado")
|
135 |
-
sent_button.click(process_sentiment, inputs=text_sent, outputs=sent_output)
|
136 |
-
|
137 |
-
with gr.TabItem("Entidades Nomeadas"):
|
138 |
-
ner_input = gr.Textbox(label="Texto")
|
139 |
-
ner_button = gr.Button("Identificar Entidades")
|
140 |
-
ner_output = gr.Textbox(label="Entidades Identificadas")
|
141 |
-
ner_button.click(process_ner, inputs=ner_input, outputs=ner_output)
|
142 |
-
|
143 |
-
with gr.TabItem("Classificação Zero-Shot"):
|
144 |
-
zero_text = gr.Textbox(label="Texto")
|
145 |
-
zero_labels = gr.Textbox(label="Categorias (separadas por vírgula)")
|
146 |
-
zero_button = gr.Button("Classificar")
|
147 |
-
zero_output = gr.Textbox(label="Resultado")
|
148 |
-
zero_button.click(process_zero_shot, inputs=[zero_text, zero_labels], outputs=zero_output)
|
149 |
-
|
150 |
-
# Aba de IA Avançada
|
151 |
-
with gr.TabItem("🤖 IA Avançada"):
|
152 |
-
with gr.Tabs():
|
153 |
-
with gr.TabItem("Chat"):
|
154 |
-
chatbot = gr.Chatbot()
|
155 |
-
msg = gr.Textbox(label="Mensagem")
|
156 |
-
clear = gr.Button("Limpar Conversa")
|
157 |
-
msg.submit(process_chat, inputs=[msg, chatbot], outputs=[msg, chatbot])
|
158 |
-
clear.click(lambda: None, None, chatbot, queue=False)
|
159 |
-
|
160 |
-
with gr.TabItem("Descrição de Imagens"):
|
161 |
-
image_input = gr.Image()
|
162 |
-
caption_button = gr.Button("Gerar Descrição")
|
163 |
-
caption_output = gr.Textbox(label="Descrição")
|
164 |
-
caption_button.click(process_image_caption, inputs=image_input, outputs=caption_output)
|
165 |
-
|
166 |
-
demo.launch(share=True)
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
3 |
import torch
|
4 |
import warnings
|
|
|
|
|
5 |
warnings.filterwarnings('ignore')
|
6 |
|
7 |
+
# Configurações
|
8 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
9 |
+
MAX_LENGTH = 2048
|
10 |
+
|
11 |
+
# Usar modelo público e leve
|
12 |
+
model_name = "microsoft/DialoGPT-small"
|
13 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
14 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
15 |
+
|
16 |
+
# Tópicos polêmicos com versículos
|
17 |
+
CONTROVERSIAL_TOPICS = {
|
18 |
+
"Sexualidade e Identidade": {
|
19 |
+
"description": "Perspectivas bíblicas sobre sexualidade, identidade e relacionamentos",
|
20 |
+
"verses": [
|
21 |
+
"Gênesis 1:27 - Criou Deus o homem à sua imagem...",
|
22 |
+
"1 Coríntios 6:9-11 - Não sabeis que os injustos...",
|
23 |
+
"Gálatas 3:28 - Não há judeu nem grego..."
|
24 |
+
]
|
25 |
+
},
|
26 |
+
|
27 |
+
"Aborto e Vida": {
|
28 |
+
"description": "Visão bíblica sobre a santidade da vida",
|
29 |
+
"verses": [
|
30 |
+
"Salmos 139:13-16 - Tu formaste o meu interior...",
|
31 |
+
"Jeremias 1:5 - Antes que te formasses...",
|
32 |
+
"Êxodo 20:13 - Não matarás"
|
33 |
+
]
|
34 |
+
},
|
35 |
+
|
36 |
+
"Riqueza e Pobreza": {
|
37 |
+
"description": "Perspectivas sobre desigualdade social",
|
38 |
+
"verses": [
|
39 |
+
"1 Timóteo 6:10 - O amor ao dinheiro é raiz...",
|
40 |
+
"Mateus 19:24 - É mais fácil passar um camelo...",
|
41 |
+
"Provérbios 22:2 - O rico e o pobre se encontram..."
|
42 |
+
]
|
43 |
+
},
|
44 |
+
|
45 |
+
"Política e Governo": {
|
46 |
+
"description": "Relação entre fé e política",
|
47 |
+
"verses": [
|
48 |
+
"Romanos 13:1-7 - Todo homem esteja sujeito...",
|
49 |
+
"Mateus 22:21 - Dai a César o que é de César...",
|
50 |
+
"1 Pedro 2:13-17 - Sujeitai-vos a toda autoridade..."
|
51 |
+
]
|
52 |
+
},
|
53 |
+
|
54 |
+
"Meio Ambiente": {
|
55 |
+
"description": "Mordomia ambiental",
|
56 |
+
"verses": [
|
57 |
+
"Gênesis 1:28 - Dominai sobre ela...",
|
58 |
+
"Gênesis 2:15 - Para o cultivar e o guardar...",
|
59 |
+
"Salmos 24:1 - Do Senhor é a terra..."
|
60 |
+
]
|
61 |
+
},
|
62 |
+
|
63 |
+
"Guerra e Paz": {
|
64 |
+
"description": "Perspectivas sobre conflito",
|
65 |
+
"verses": [
|
66 |
+
"Mateus 5:9 - Bem-aventurados os pacificadores...",
|
67 |
+
"Romanos 12:18 - Quanto depender de vós, tende paz...",
|
68 |
+
"Eclesiastes 3:8 - Tempo de guerra, e tempo de paz..."
|
69 |
+
]
|
70 |
+
},
|
71 |
+
|
72 |
+
"Ciência e Fé": {
|
73 |
+
"description": "Relação entre conhecimento e fé",
|
74 |
+
"verses": [
|
75 |
+
"Colossenses 2:8 - Cuidado que ninguém vos engane...",
|
76 |
+
"Romanos 1:20 - Seus atributos invisíveis...",
|
77 |
+
"Salmos 19:1 - Os céus proclamam..."
|
78 |
+
]
|
79 |
+
},
|
80 |
+
|
81 |
+
"Divórcio": {
|
82 |
+
"description": "Visões sobre matrimônio",
|
83 |
+
"verses": [
|
84 |
+
"Mateus 19:8-9 - Por causa da dureza...",
|
85 |
+
"Malaquias 2:16 - Porque o Senhor odeia o divórcio...",
|
86 |
+
"1 Coríntios 7:15 - Mas, se o descrente..."
|
87 |
+
]
|
88 |
+
},
|
89 |
+
|
90 |
+
"Papel da Mulher": {
|
91 |
+
"description": "Questões de gênero e liderança",
|
92 |
+
"verses": [
|
93 |
+
"Gálatas 3:28 - Não há homem nem mulher...",
|
94 |
+
"Provérbios 31 - Mulher virtuosa...",
|
95 |
+
"Juízes 4:4 - Débora, profetisa..."
|
96 |
+
]
|
97 |
+
},
|
98 |
+
|
99 |
+
"Livre Arbítrio": {
|
100 |
+
"description": "Escolha e soberania",
|
101 |
+
"verses": [
|
102 |
+
"João 3:16 - Para que todo aquele que nele crê...",
|
103 |
+
"Romanos 8:29-30 - Porquanto aos que conheceu...",
|
104 |
+
"2 Pedro 3:9 - Não querendo que ninguém pereça..."
|
105 |
+
]
|
106 |
+
}
|
107 |
}
|
108 |
|
109 |
+
def process_message(message, history, topic=None):
|
110 |
+
try:
|
111 |
+
if topic:
|
112 |
+
info = CONTROVERSIAL_TOPICS[topic]
|
113 |
+
response = f"""
|
114 |
+
📚 Tema: {topic}
|
115 |
+
|
116 |
+
📖 Descrição:
|
117 |
+
{info['description']}
|
118 |
+
|
119 |
+
✝️ Versículos Relevantes:
|
120 |
+
"""
|
121 |
+
for verse in info['verses']:
|
122 |
+
response += f"• {verse}\n"
|
123 |
+
|
124 |
+
response += "\nEstes versículos nos mostram diferentes aspectos deste tema. É importante estudá-los em seu contexto completo para uma melhor compreensão."
|
125 |
+
|
126 |
+
return response
|
127 |
+
else:
|
128 |
+
# Para perguntas gerais
|
129 |
+
response = f"Sua pergunta: {message}\n\n"
|
130 |
+
response += "Pesquisando nas escrituras...\n"
|
131 |
+
# Procurar por palavras-chave e retornar versículos relevantes
|
132 |
+
for topic, info in CONTROVERSIAL_TOPICS.items():
|
133 |
+
if any(word.lower() in message.lower() for word in topic.split()):
|
134 |
+
response += f"\nVersículos relacionados a {topic}:\n"
|
135 |
+
for verse in info['verses'][:2]:
|
136 |
+
response += f"• {verse}\n"
|
137 |
+
return response
|
138 |
+
|
139 |
+
except Exception as e:
|
140 |
+
return f"Ocorreu um erro: {str(e)}"
|
141 |
+
|
142 |
+
# Interface Gradio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
144 |
+
gr.HTML("""
|
145 |
+
<div style="text-align: center; padding: 20px;">
|
146 |
+
<h1>📖 Análise Bíblica de Temas Contemporâneos</h1>
|
147 |
+
<p>Explore diferentes perspectivas bíblicas sobre questões atuais</p>
|
148 |
+
</div>
|
149 |
+
""")
|
150 |
|
151 |
+
with gr.Row():
|
152 |
+
# Coluna principal do chat
|
153 |
+
with gr.Column(scale=2):
|
154 |
+
chatbot = gr.Chatbot(
|
155 |
+
height=600,
|
156 |
+
bubble_full_width=False,
|
157 |
+
show_label=False
|
158 |
+
)
|
159 |
+
with gr.Row():
|
160 |
+
msg = gr.Textbox(
|
161 |
+
show_label=False,
|
162 |
+
placeholder="Digite sua pergunta ou clique em um dos temas...",
|
163 |
+
scale=4
|
164 |
+
)
|
165 |
+
clear = gr.Button("🗑️ Limpar", scale=1)
|
166 |
|
167 |
+
# Coluna de tópicos
|
168 |
+
with gr.Column(scale=1):
|
169 |
+
gr.Markdown("### 🔍 Temas para Explorar")
|
170 |
+
|
171 |
+
# Criar botões em grupos temáticos
|
172 |
+
for topic in CONTROVERSIAL_TOPICS.keys():
|
173 |
+
with gr.Box():
|
174 |
+
btn = gr.Button(f"📚 {topic}", scale=1)
|
175 |
+
btn.click(
|
176 |
+
process_message,
|
177 |
+
inputs=[gr.Textbox(value="", visible=False), chatbot],
|
178 |
+
outputs=chatbot,
|
179 |
+
kwargs={"topic": topic}
|
180 |
+
)
|
181 |
+
|
182 |
+
# Eventos
|
183 |
+
msg.submit(process_message, [msg, chatbot], [chatbot])
|
184 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
185 |
+
|
186 |
+
gr.Markdown("""
|
187 |
+
### ℹ️ Como usar:
|
188 |
+
1. Clique em um dos temas para ver versículos relacionados
|
189 |
+
2. Digite uma pergunta específica no campo de texto
|
190 |
+
3. Use o botão 'Limpar' para reiniciar a conversa
|
191 |
+
""")
|
192 |
+
|
193 |
+
# Iniciar a interface
|
194 |
+
demo.launch(share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|