fccoelho aider (anthropic/claude-sonnet-4-20250514) commited on
Commit
4360e04
·
1 Parent(s): f2cfb58

feat: adicionar suporte a modelos OpenAI e dropdown de seleção

Browse files

Co-authored-by: aider (anthropic/claude-sonnet-4-20250514) <aider@aider.chat>

Files changed (2) hide show
  1. app.py +60 -21
  2. pyproject.toml +1 -0
app.py CHANGED
@@ -5,6 +5,7 @@ from pydantic_ai import Agent
5
  from pydantic import BaseModel
6
  from typing import List, Optional
7
  import google.generativeai as genai
 
8
  import os
9
  from dotenv import load_dotenv
10
  import io
@@ -52,15 +53,24 @@ def extract_pdf_text(pdf_file):
52
  except Exception as e:
53
  return None, {"error": f"Erro ao processar PDF: {str(e)}"}
54
 
55
- def extract_references_with_llm(text):
56
- """Usa Pydantic AI com Gemini para extrair e estruturar referências"""
57
  try:
58
- # Configurar a API key do Google
59
- genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
 
 
 
 
 
 
 
 
 
60
 
61
  # Criar o agente Pydantic AI
62
  agent = Agent(
63
- 'gemini-2.5-pro', # Modelo Gemini 2.0 Flash
64
  result_type=ReferencesResponse,
65
  system_prompt="""
66
  Você é um especialista em análise de artigos científicos.
@@ -79,8 +89,11 @@ def extract_references_with_llm(text):
79
  """
80
  )
81
 
82
- # Limitar o texto para evitar exceder limites da API
83
- limited_text = text[:150000] # Gemini tem limite maior que GPT
 
 
 
84
 
85
  # Executar o agente
86
  result = agent.run_sync(f"Extraia as referências bibliográficas do seguinte texto de artigo científico:\n\n{limited_text}")
@@ -101,9 +114,9 @@ def extract_references_with_llm(text):
101
  return references_list
102
 
103
  except Exception as e:
104
- return [{"error": f"Erro ao processar com LLM: {str(e)}"}]
105
 
106
- def process_pdf(pdf_file):
107
  """Função principal que processa o PDF e retorna resultados"""
108
  if pdf_file is None:
109
  return {"error": "Nenhum arquivo enviado"}, pd.DataFrame()
@@ -114,8 +127,11 @@ def process_pdf(pdf_file):
114
  if text is None:
115
  return metadata, pd.DataFrame()
116
 
 
 
 
117
  # Extrair referências com LLM
118
- references = extract_references_with_llm(text)
119
 
120
  # Converter para DataFrame
121
  if references and not any("error" in ref for ref in references):
@@ -132,11 +148,26 @@ def create_interface():
132
  gr.Markdown("Faça upload de um PDF de artigo científico para extrair automaticamente a lista de referências.")
133
 
134
  with gr.Row():
135
- pdf_input = gr.File(
136
- label="📄 Upload do PDF",
137
- file_types=[".pdf"],
138
- type="binary"
139
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  extract_btn = gr.Button("🔍 Extrair Referências", variant="primary")
142
 
@@ -154,7 +185,7 @@ def create_interface():
154
 
155
  extract_btn.click(
156
  process_pdf,
157
- inputs=[pdf_input],
158
  outputs=[metadata_output, references_output]
159
  )
160
 
@@ -163,11 +194,19 @@ def create_interface():
163
  def main():
164
  load_dotenv() # Carrega variáveis de ambiente do arquivo .env
165
 
166
- # Verificar se a chave da API está configurada
167
- if not os.getenv("GEMINI_API_KEY"):
168
- print("⚠️ AVISO: Chave da API Google não encontrada!")
169
- print("Crie um arquivo .env com: GEMINI_API_KEY=sua_chave_aqui")
170
- print("Obtenha sua chave em: https://aistudio.google.com/app/apikey")
 
 
 
 
 
 
 
 
171
 
172
  interface = create_interface()
173
  interface.launch(share=True)
 
5
  from pydantic import BaseModel
6
  from typing import List, Optional
7
  import google.generativeai as genai
8
+ import openai
9
  import os
10
  from dotenv import load_dotenv
11
  import io
 
53
  except Exception as e:
54
  return None, {"error": f"Erro ao processar PDF: {str(e)}"}
55
 
56
+ def extract_references_with_llm(text, model_name):
57
+ """Usa Pydantic AI com diferentes modelos para extrair e estruturar referências"""
58
  try:
59
+ # Determinar se é modelo Google ou OpenAI
60
+ if model_name.startswith('gemini'):
61
+ # Configurar a API key do Google
62
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
63
+ api_key = os.getenv("GOOGLE_API_KEY")
64
+ else:
65
+ # Usar OpenAI
66
+ api_key = os.getenv("OPENAI_API_KEY")
67
+
68
+ if not api_key:
69
+ return [{"error": f"Chave da API não encontrada para o modelo {model_name}"}]
70
 
71
  # Criar o agente Pydantic AI
72
  agent = Agent(
73
+ model_name,
74
  result_type=ReferencesResponse,
75
  system_prompt="""
76
  Você é um especialista em análise de artigos científicos.
 
89
  """
90
  )
91
 
92
+ # Ajustar limite de texto baseado no modelo
93
+ if model_name.startswith('gemini'):
94
+ limited_text = text[:150000] # Gemini tem limite maior
95
+ else:
96
+ limited_text = text[:50000] # OpenAI tem limite menor
97
 
98
  # Executar o agente
99
  result = agent.run_sync(f"Extraia as referências bibliográficas do seguinte texto de artigo científico:\n\n{limited_text}")
 
114
  return references_list
115
 
116
  except Exception as e:
117
+ return [{"error": f"Erro ao processar com LLM ({model_name}): {str(e)}"}]
118
 
119
+ def process_pdf(pdf_file, model_name):
120
  """Função principal que processa o PDF e retorna resultados"""
121
  if pdf_file is None:
122
  return {"error": "Nenhum arquivo enviado"}, pd.DataFrame()
 
127
  if text is None:
128
  return metadata, pd.DataFrame()
129
 
130
+ # Adicionar modelo selecionado aos metadados
131
+ metadata["modelo_usado"] = model_name
132
+
133
  # Extrair referências com LLM
134
+ references = extract_references_with_llm(text, model_name)
135
 
136
  # Converter para DataFrame
137
  if references and not any("error" in ref for ref in references):
 
148
  gr.Markdown("Faça upload de um PDF de artigo científico para extrair automaticamente a lista de referências.")
149
 
150
  with gr.Row():
151
+ with gr.Column():
152
+ pdf_input = gr.File(
153
+ label="📄 Upload do PDF",
154
+ file_types=[".pdf"],
155
+ type="binary"
156
+ )
157
+ with gr.Column():
158
+ model_dropdown = gr.Dropdown(
159
+ choices=[
160
+ "gemini-2.0-flash-exp",
161
+ "gemini-1.5-pro",
162
+ "gemini-1.5-flash",
163
+ "gpt-4o",
164
+ "gpt-4o-mini",
165
+ "gpt-3.5-turbo"
166
+ ],
167
+ value="gemini-2.0-flash-exp",
168
+ label="🤖 Modelo de IA",
169
+ info="Selecione o modelo para extrair as referências"
170
+ )
171
 
172
  extract_btn = gr.Button("🔍 Extrair Referências", variant="primary")
173
 
 
185
 
186
  extract_btn.click(
187
  process_pdf,
188
+ inputs=[pdf_input, model_dropdown],
189
  outputs=[metadata_output, references_output]
190
  )
191
 
 
194
  def main():
195
  load_dotenv() # Carrega variáveis de ambiente do arquivo .env
196
 
197
+ # Verificar se as chaves das APIs estão configuradas
198
+ google_key = os.getenv("GOOGLE_API_KEY")
199
+ openai_key = os.getenv("OPENAI_API_KEY")
200
+
201
+ if not google_key and not openai_key:
202
+ print("⚠️ AVISO: Nenhuma chave de API encontrada!")
203
+ print("Configure pelo menos uma das seguintes no arquivo .env:")
204
+ print("- GOOGLE_API_KEY=sua_chave_do_google")
205
+ print("- OPENAI_API_KEY=sua_chave_da_openai")
206
+ elif not google_key:
207
+ print("ℹ️ Apenas OpenAI configurado. Modelos Gemini não funcionarão.")
208
+ elif not openai_key:
209
+ print("ℹ️ Apenas Google configurado. Modelos OpenAI não funcionarão.")
210
 
211
  interface = create_interface()
212
  interface.launch(share=True)
pyproject.toml CHANGED
@@ -12,4 +12,5 @@ dependencies = [
12
  "google-generativeai>=0.8.0",
13
  "python-dotenv>=1.0.0",
14
  "pandas-stubs==2.3.2.250827",
 
15
  ]
 
12
  "google-generativeai>=0.8.0",
13
  "python-dotenv>=1.0.0",
14
  "pandas-stubs==2.3.2.250827",
15
+ "openai>=1.0.0",
16
  ]