Spaces:
Sleeping
Sleeping
Commit ·
4360e04
1
Parent(s): f2cfb58
feat: adicionar suporte a modelos OpenAI e dropdown de seleção
Browse filesCo-authored-by: aider (anthropic/claude-sonnet-4-20250514) <aider@aider.chat>
Files changed (2)
- app.py+60-21
- pyproject.toml+1
4 unmodified lines567891041 unmodified lines52535455565758596061626364656612 unmodified lines798081828384858614 unmodified lines1011021031041051061071081094 unmodified lines11411511611711811912012110 unmodified lines13213313413513613713813914014114211 unmodified lines1541551561571581591602 unmodified lines1631641651661671681691701711721734 unmodified linesfrom pydantic import BaseModelfrom typing import List, Optionalimport google.generativeai as genaiimport osfrom dotenv import load_dotenvimport io41 unmodified linesexcept Exception as e:return None, {"error": f"Erro ao processar PDF: {str(e)}"}def extract_references_with_llm(text):"""Usa Pydantic AI com Gemini para extrair e estruturar referências"""try:# Configurar a API key do Googlegenai.configure(api_key=os.getenv("GOOGLE_API_KEY"))# Criar o agente Pydantic AIagent = Agent('gemini-2.5-pro', # Modelo Gemini 2.0 Flashresult_type=ReferencesResponse,system_prompt="""Você é um especialista em análise de artigos científicos.12 unmodified lines""")# Limitar o texto para evitar exceder limites da APIlimited_text = text[:150000] # Gemini tem limite maior que GPT# Executar o agenteresult = agent.run_sync(f"Extraia as referências bibliográficas do seguinte texto de artigo científico:\n\n{limited_text}")14 unmodified linesreturn references_listexcept Exception as e:return [{"error": f"Erro ao processar com LLM: {str(e)}"}]def process_pdf(pdf_file):"""Função principal que processa o PDF e retorna resultados"""if pdf_file is None:return {"error": "Nenhum arquivo enviado"}, pd.DataFrame()4 unmodified linesif text is None:return metadata, pd.DataFrame()# Extrair referências com LLMreferences = extract_references_with_llm(text)# Converter para DataFrameif references and not any("error" in ref for ref in references):10 unmodified linesgr.Markdown("Faça upload de um PDF de artigo científico para extrair automaticamente a lista de referências.")with gr.Row():pdf_input = gr.File(label="📄 Upload do PDF",file_types=[".pdf"],type="binary")extract_btn = gr.Button("🔍 Extrair Referências", variant="primary")11 unmodified linesextract_btn.click(process_pdf,inputs=[pdf_input],outputs=[metadata_output, references_output])2 unmodified linesdef main():load_dotenv() # Carrega variáveis de ambiente do arquivo .env# Verificar se a chave da API está configuradaif not os.getenv("GEMINI_API_KEY"):print("⚠️ AVISO: Chave da API Google não encontrada!")print("Crie um arquivo .env com: GEMINI_API_KEY=sua_chave_aqui")print("Obtenha sua chave em: https://aistudio.google.com/app/apikey")interface = create_interface()interface.launch(share=True)4 unmodified lines56789101141 unmodified lines53545556575859606162636465666768697071727374757612 unmodified lines899091929394959697989914 unmodified lines1141151161171181191201211224 unmodified lines12712812913013113213313413513613710 unmodified lines14814915015115215315415515615715815916016116216316416516616716816917017117217311 unmodified lines1851861871881891901912 unmodified lines1941951961971981992002012022032042052062072082092102112124 unmodified linesfrom pydantic import BaseModelfrom typing import List, Optionalimport google.generativeai as genaiimport openaiimport osfrom dotenv import load_dotenvimport io41 unmodified linesexcept Exception as e:return None, {"error": f"Erro ao processar PDF: {str(e)}"}def extract_references_with_llm(text, model_name):"""Usa Pydantic AI com diferentes modelos para extrair e estruturar referências"""try:# Determinar se é modelo Google ou OpenAIif model_name.startswith('gemini'):# Configurar a API key do Googlegenai.configure(api_key=os.getenv("GOOGLE_API_KEY"))api_key = os.getenv("GOOGLE_API_KEY")else:# Usar OpenAIapi_key = os.getenv("OPENAI_API_KEY")if not api_key:return [{"error": f"Chave da API não encontrada para o modelo {model_name}"}]# Criar o agente Pydantic AIagent = Agent(model_name,result_type=ReferencesResponse,system_prompt="""Você é um especialista em análise de artigos científicos.12 unmodified lines""")# Ajustar limite de texto baseado no modeloif model_name.startswith('gemini'):limited_text = text[:150000] # Gemini tem limite maiorelse:limited_text = text[:50000] # OpenAI tem limite menor# Executar o agenteresult = agent.run_sync(f"Extraia as referências bibliográficas do seguinte texto de artigo científico:\n\n{limited_text}")14 unmodified linesreturn references_listexcept Exception as e:return [{"error": f"Erro ao processar com LLM ({model_name}): {str(e)}"}]def process_pdf(pdf_file, model_name):"""Função principal que processa o PDF e retorna resultados"""if pdf_file is None:return {"error": "Nenhum arquivo enviado"}, pd.DataFrame()4 unmodified linesif text is None:return metadata, pd.DataFrame()# Adicionar modelo selecionado aos metadadosmetadata["modelo_usado"] = model_name# Extrair referências com LLMreferences = extract_references_with_llm(text, model_name)# Converter para DataFrameif references and not any("error" in ref for ref in references):10 unmodified linesgr.Markdown("Faça upload de um PDF de artigo científico para extrair automaticamente a lista de referências.")with gr.Row():with gr.Column():pdf_input = gr.File(label="📄 Upload do PDF",file_types=[".pdf"],type="binary")with gr.Column():model_dropdown = gr.Dropdown(choices=["gemini-2.0-flash-exp","gemini-1.5-pro","gemini-1.5-flash","gpt-4o","gpt-4o-mini","gpt-3.5-turbo"],value="gemini-2.0-flash-exp",label="🤖 Modelo de IA",info="Selecione o modelo para extrair as referências")extract_btn = gr.Button("🔍 Extrair Referências", variant="primary")11 unmodified linesextract_btn.click(process_pdf,inputs=[pdf_input, model_dropdown],outputs=[metadata_output, references_output])2 unmodified linesdef main():load_dotenv() # Carrega variáveis de ambiente do arquivo .env# Verificar se as chaves das APIs estão configuradasgoogle_key = os.getenv("GOOGLE_API_KEY")openai_key = os.getenv("OPENAI_API_KEY")if not google_key and not openai_key:print("⚠️ AVISO: Nenhuma chave de API encontrada!")print("Configure pelo menos uma das seguintes no arquivo .env:")print("- GOOGLE_API_KEY=sua_chave_do_google")print("- OPENAI_API_KEY=sua_chave_da_openai")elif not google_key:print("ℹ️ Apenas OpenAI configurado. Modelos Gemini não funcionarão.")elif not openai_key:print("ℹ️ Apenas Google configurado. Modelos OpenAI não funcionarão.")interface = create_interface()interface.launch(share=True)
11 unmodified lines1213141511 unmodified lines"google-generativeai>=0.8.0","python-dotenv>=1.0.0","pandas-stubs==2.3.2.250827",]11 unmodified lines121314151611 unmodified lines"google-generativeai>=0.8.0","python-dotenv>=1.0.0","pandas-stubs==2.3.2.250827","openai>=1.0.0",]
app.py+60-21
pyproject.toml+1