DHEIVER commited on
Commit
9860e17
·
verified ·
1 Parent(s): 08bd76c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -156
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
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
-
11
- # Dicionário expandido de modelos
12
- models = {
13
- 'transcription': pipeline("automatic-speech-recognition", model="openai/whisper-small", device=device),
14
- 'translation': pipeline("translation", model="facebook/mbart-large-50-many-to-many-mmt", device=device),
15
- 'summarization': pipeline("summarization", model="facebook/bart-large-cnn", device=device),
16
- 'sentiment': pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment", device=device),
17
- 'question_answering': pipeline("question-answering", model="deepset/roberta-base-squad2", device=device),
18
- 'chat': pipeline("text-generation", model="facebook/opt-125m", device=device),
19
- 'image_caption': pipeline("image-to-text", model="Salesforce/blip-image-captioning-base", device=device),
20
- 'text_to_speech': pipeline("text-to-audio", model="facebook/mms-tts-eng", device=device),
21
- 'zero_shot': pipeline("zero-shot-classification", model="facebook/bart-large-mnli", device=device),
22
- 'ner': pipeline("token-classification", model="dslim/bert-base-NER", device=device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  }
24
 
25
- def process_transcription(audio):
26
- if not audio:
27
- return "Por favor, forneça um arquivo de áudio."
28
- return models['transcription'](audio)["text"]
29
-
30
- def process_translation(text, direction):
31
- if not text:
32
- return "Por favor, forneça um texto para tradução."
33
- return models['translation'](text,
34
- src_lang="pt" if direction=="pt_en" else "en",
35
- tgt_lang="en" if direction=="pt_en" else "pt")[0]['translation_text']
36
-
37
- def process_summarization(text):
38
- if not text:
39
- return "Por favor, forneça um texto para resumir."
40
- return models['summarization'](text, max_length=130, min_length=30)[0]['summary_text']
41
-
42
- def process_sentiment(text):
43
- if not text:
44
- return "Por favor, forneça um texto para análise."
45
- result = models['sentiment'](text)[0]
46
- return f"Sentimento: {result['label']} (Score: {result['score']:.2f})"
47
-
48
- def process_qa(question, context):
49
- if not question or not context:
50
- return "Por favor, forneça tanto a pergunta quanto o contexto."
51
- return models['question_answering'](question=question, context=context)['answer']
52
-
53
- def process_chat(message, history):
54
- if not message:
55
- return "", history
56
- response = models['chat'](message, max_length=100, do_sample=True)[0]['generated_text']
57
- history = history + [(message, response)]
58
- return "", history
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(open("index.html").read())
 
 
 
 
 
87
 
88
- with gr.Tabs():
89
- # Aba de Processamento de Áudio
90
- with gr.TabItem("🎤 Áudio"):
91
- with gr.Tabs():
92
- with gr.TabItem("Transcrição"):
93
- audio_input = gr.Audio(type="filepath")
94
- transcribe_button = gr.Button("Transcrever")
95
- transcription_output = gr.Textbox(label="Resultado")
96
- transcribe_button.click(process_transcription, inputs=audio_input, outputs=transcription_output)
97
-
98
- with gr.TabItem("Texto para Fala"):
99
- tts_input = gr.Textbox(label="Texto para Converter")
100
- tts_button = gr.Button("Converter para Áudio")
101
- tts_output = gr.Audio(label="Áudio Gerado")
102
- tts_button.click(process_tts, inputs=tts_input, outputs=tts_output)
103
 
104
- # Aba de Processamento de Texto
105
- with gr.TabItem("📝 Texto"):
106
- with gr.Tabs():
107
- with gr.TabItem("Tradução"):
108
- with gr.Row():
109
- text_to_translate = gr.Textbox(label="Texto")
110
- translation_direction = gr.Radio(["en_pt", "pt_en"], value="en_pt", label="Direção")
111
- translate_button = gr.Button("Traduzir")
112
- translation_output = gr.Textbox(label="Resultado")
113
- translate_button.click(process_translation, inputs=[text_to_translate, translation_direction], outputs=translation_output)
114
-
115
- with gr.TabItem("Resumo"):
116
- text_sum = gr.Textbox(label="Texto", lines=5)
117
- sum_button = gr.Button("Resumir")
118
- sum_output = gr.Textbox(label="Resultado")
119
- sum_button.click(process_summarization, inputs=text_sum, outputs=sum_output)
120
-
121
- with gr.TabItem("Perguntas e Respostas"):
122
- qa_context = gr.Textbox(label="Contexto", lines=5)
123
- qa_question = gr.Textbox(label="Pergunta")
124
- qa_button = gr.Button("Obter Resposta")
125
- qa_output = gr.Textbox(label="Resposta")
126
- qa_button.click(process_qa, inputs=[qa_question, qa_context], outputs=qa_output)
127
-
128
- # Aba de Análise
129
- with gr.TabItem("📊 Análise"):
130
- with gr.Tabs():
131
- with gr.TabItem("Sentimento"):
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)