GabrielGD commited on
Commit
4aff160
·
verified ·
1 Parent(s): 13e8aa7

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +201 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ import gradio as gr
3
+ import base64
4
+ import io
5
+ import os
6
+ import uuid
7
+ import PyPDF2
8
+ from PIL import Image
9
+ import imageio
10
+ import random
11
+
12
+ # Bibliotecas para texto para áudio e PDF
13
+ from gtts import gTTS
14
+ from reportlab.lib.pagesizes import letter
15
+ from reportlab.platypus import SimpleDocTemplate, Paragraph
16
+ from reportlab.lib.styles import getSampleStyleSheet
17
+
18
+ # Configuração da API do Google
19
+ # Defina suas chaves de API aqui
20
+ API_KEYS = [
21
+ 'AIzaSyAgmf1ZvNrvzAmlNCQvQbyZDJJPdMwecqY', # Exemplo chave 1
22
+ 'AIzaSyB18Z-Ct2-IKYGZ9vKaChcee-BDVS77Ksg', # Exemplo chave 2
23
+ 'AIzaSyBB5Tp0xdXcemLMGDm8_cL6L37wTe_8sjg', # Exemplo chave 3
24
+ 'AIzaSyCefvhXMsgHmAF_0KVkZ0UAeZ5nNC41v-A', # Exemplo chave 4
25
+ ]
26
+
27
+ def escolher_chave_api():
28
+ return random.choice(API_KEYS)
29
+
30
+ genai.configure(api_key=escolher_chave_api())
31
+
32
+ # Modelo de geração de texto
33
+ model = genai.GenerativeModel('gemini-1.5-flash')
34
+
35
+ class AssistenteAcademico:
36
+ def __init__(self):
37
+ self.contexto_atual = {}
38
+ self.ultima_imagem_path = None
39
+ self.pasta_temp = 'assistente_temp'
40
+
41
+ # Cria pastas para arquivos temporários
42
+ for pasta in [self.pasta_temp, 'audios_assistente', 'pdfs_respostas']:
43
+ os.makedirs(pasta, exist_ok=True)
44
+
45
+ def gerar_pdf_resposta(self, texto, nome_arquivo=None):
46
+ """
47
+ Gera um arquivo PDF com a resposta
48
+ """
49
+ try:
50
+ nome_arquivo = nome_arquivo or f'resposta_{uuid.uuid4()}.pdf'
51
+ caminho_pdf = os.path.join('pdfs_respostas', nome_arquivo)
52
+
53
+ doc = SimpleDocTemplate(caminho_pdf, pagesize=letter)
54
+ styles = getSampleStyleSheet()
55
+ story = [Paragraph(texto.replace('\n', '<br/>'), styles['Normal'])]
56
+
57
+ doc.build(story)
58
+ return caminho_pdf
59
+ except Exception as e:
60
+ print(f"Erro ao criar PDF: {e}")
61
+ return None
62
+
63
+ def texto_para_audio(self, texto, nome_arquivo=None):
64
+ """
65
+ Converte texto para áudio em português brasileiro
66
+ """
67
+ try:
68
+ nome_arquivo = nome_arquivo or f'{uuid.uuid4()}.mp3'
69
+ caminho_audio = os.path.join('audios_assistente', nome_arquivo)
70
+
71
+ tts = gTTS(texto, lang='pt-BR')
72
+ tts.save(caminho_audio)
73
+
74
+ return caminho_audio
75
+ except Exception as e:
76
+ print(f"Erro ao criar áudio: {e}")
77
+ return None
78
+
79
+ def codificar_imagem(self, imagem_path):
80
+ """
81
+ Codifica imagem para processamento, suportando múltiplos formatos
82
+ """
83
+ try:
84
+ extensao = os.path.splitext(imagem_path)[1].lower()
85
+ if extensao not in ['.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff', '.webp']:
86
+ raise ValueError(f"Formato de imagem não suportado: {extensao}")
87
+
88
+ imagem = imageio.imread(imagem_path)
89
+ imagem_pil = Image.fromarray(imagem)
90
+ imagem_pil.thumbnail((800, 800), Image.LANCZOS)
91
+
92
+ temp_path = os.path.join(self.pasta_temp, f'temp_image_{uuid.uuid4()}{extensao}')
93
+ imagem_pil.convert('RGB').save(temp_path)
94
+
95
+ return temp_path
96
+ except Exception as e:
97
+ print(f"Erro ao codificar imagem: {e}")
98
+ return None
99
+
100
+ def processar_input(self, pergunta, pdf=None, imagem=None):
101
+ """
102
+ Processa input do usuário considerando contexto atual
103
+ """
104
+ try:
105
+ inputs = [self.contexto_atual.get('pdf_texto', '')]
106
+
107
+ if pdf:
108
+ texto_pdf = self.extrair_texto_pdf(pdf)
109
+ self.contexto_atual['pdf_texto'] = texto_pdf
110
+ inputs.append(texto_pdf)
111
+
112
+ if imagem:
113
+ if self.ultima_imagem_path and os.path.exists(self.ultima_imagem_path):
114
+ os.remove(self.ultima_imagem_path)
115
+
116
+ imagem_path = self.codificar_imagem(imagem)
117
+ if imagem_path:
118
+ self.ultima_imagem_path = imagem_path
119
+ inputs.append(genai.upload_file(path=imagem_path))
120
+
121
+ prompt = f"""Como um assistente acadêmico avançado:
122
+ - Seja objetivo e acadêmico
123
+ - Forneça explicações claras
124
+ - Use linguagem técnica quando apropriado
125
+ - Cite referências se possível
126
+ - Mantenha a explicação acessível
127
+
128
+ Pergunta atual: {pergunta}
129
+ """
130
+ inputs.append(prompt)
131
+
132
+ resposta = model.generate_content(inputs)
133
+ texto_resposta = resposta.text
134
+
135
+ caminho_audio = self.texto_para_audio(texto_resposta)
136
+ caminho_pdf = self.gerar_pdf_resposta(texto_resposta)
137
+
138
+ return texto_resposta, caminho_audio, caminho_pdf
139
+ except Exception as e:
140
+ return f"Erro no processamento: {str(e)}", None, None
141
+
142
+ def extrair_texto_pdf(self, arquivo_pdf):
143
+ """
144
+ Extrai texto completo de um arquivo PDF
145
+ """
146
+ try:
147
+ leitor_pdf = PyPDF2.PdfReader(arquivo_pdf)
148
+ return "\n".join(pagina.extract_text() for pagina in leitor_pdf.pages)
149
+ except Exception as e:
150
+ return f"Erro ao extrair texto do PDF: {str(e)}"
151
+
152
+ def limpar_arquivos_temporarios(self):
153
+ """
154
+ Remove arquivos temporários antigos
155
+ """
156
+ import time
157
+ for pasta in [self.pasta_temp, 'audios_assistente', 'pdfs_respostas']:
158
+ for arquivo in os.listdir(pasta):
159
+ caminho = os.path.join(pasta, arquivo)
160
+ if os.path.isfile(caminho) and time.time() - os.path.getctime(caminho) > 3600:
161
+ os.remove(caminho)
162
+
163
+ def chatbot_interface(self):
164
+ """
165
+ Cria interface de chatbot interativo
166
+ """
167
+ with gr.Blocks(css=".gradio-container {font-family: 'Arial', sans-serif; max-width: 800px; margin: auto;}") as interface:
168
+ gr.Markdown("""# 🎓 Assistente Acadêmico 👨🏿‍💻
169
+ Bem-vindo ao Assistente Acadêmico! Faça suas perguntas acadêmicas e obtenha respostas detalhadas. Você também pode carregar PDFs e imagens para análise.**
170
+ """)
171
+ chatbot = gr.Chatbot(label="Chat", elem_id="chat_area")
172
+
173
+ with gr.Row():
174
+ audio_output = gr.Audio(label="Audiodescrição")
175
+ pdf_output = gr.File(label="Download PDF")
176
+
177
+ with gr.Row():
178
+ msg = gr.Textbox(label="Sua Pergunta", placeholder="Digite sua pergunta aqui...")
179
+ pdf_input = gr.File(file_types=['.pdf'], label="Carregar PDF")
180
+ img_input = gr.File(file_types=['.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff', '.webp'], label="Carregar Imagem")
181
+ submit_btn = gr.Button("Enviar", elem_id="submit_btn")
182
+
183
+ def responder(mensagem, historico, pdf=None, imagem=None):
184
+ resposta, caminho_audio, caminho_pdf = self.processar_input(mensagem, pdf, imagem)
185
+ historico.append((mensagem, resposta))
186
+ self.limpar_arquivos_temporarios()
187
+ return "", historico, caminho_audio, caminho_pdf
188
+
189
+ submit_btn.click(
190
+ responder,
191
+ inputs=[msg, chatbot, pdf_input, img_input],
192
+ outputs=[msg, chatbot, audio_output, pdf_output]
193
+ )
194
+
195
+ return interface
196
+
197
+ # Inicialização
198
+ assistente = AssistenteAcademico()
199
+ interface = assistente.chatbot_interface()
200
+ print("🚀 Assistente Acadêmico inicializado!")
201
+ interface.launch(debug=True, share=True)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ google-generativeai
2
+ PyPDF2
3
+ Pillow
4
+ gradio
5
+ gTTS
6
+ soundfile
7
+ reportlab
8
+ imageio