Spaces:
Running
Running
Commit
·
95baff4
1
Parent(s):
ec4a946
feat: migrar extração de referências do OpenAI para Pydantic AI com Gemini
Browse filesCo-authored-by: aider (anthropic/claude-sonnet-4-20250514) <aider@aider.chat>
- app.py +60 -35
- pyproject.toml +2 -1
app.py
CHANGED
|
@@ -1,13 +1,28 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import pymupdf # PyMuPDF
|
| 3 |
import pandas as pd
|
| 4 |
-
import
|
|
|
|
|
|
|
|
|
|
| 5 |
import os
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
import io
|
| 8 |
import json
|
| 9 |
import re
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
def extract_pdf_text(pdf_file):
|
| 12 |
"""Extrai texto e metadados básicos do PDF"""
|
| 13 |
try:
|
|
@@ -38,43 +53,52 @@ def extract_pdf_text(pdf_file):
|
|
| 38 |
return None, {"error": f"Erro ao processar PDF: {str(e)}"}
|
| 39 |
|
| 40 |
def extract_references_with_llm(text):
|
| 41 |
-
"""Usa
|
| 42 |
try:
|
| 43 |
-
|
|
|
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
"""
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
content = response.choices[0].message.content
|
| 71 |
-
# Procurar por JSON na resposta
|
| 72 |
-
json_match = re.search(r'\[.*\]', content, re.DOTALL)
|
| 73 |
-
if json_match:
|
| 74 |
-
references_data = json.loads(json_match.group())
|
| 75 |
-
return references_data
|
| 76 |
-
else:
|
| 77 |
-
return []
|
| 78 |
|
| 79 |
except Exception as e:
|
| 80 |
return [{"error": f"Erro ao processar com LLM: {str(e)}"}]
|
|
@@ -140,9 +164,10 @@ def main():
|
|
| 140 |
load_dotenv() # Carrega variáveis de ambiente do arquivo .env
|
| 141 |
|
| 142 |
# Verificar se a chave da API está configurada
|
| 143 |
-
if not os.getenv("
|
| 144 |
-
print("⚠️ AVISO: Chave da API
|
| 145 |
-
print("Crie um arquivo .env com:
|
|
|
|
| 146 |
|
| 147 |
interface = create_interface()
|
| 148 |
interface.launch(share=True)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pymupdf # PyMuPDF
|
| 3 |
import pandas as pd
|
| 4 |
+
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
|
| 11 |
import json
|
| 12 |
import re
|
| 13 |
|
| 14 |
+
class Reference(BaseModel):
|
| 15 |
+
authors: List[str]
|
| 16 |
+
title: str
|
| 17 |
+
journal: Optional[str] = None
|
| 18 |
+
year: Optional[int] = None
|
| 19 |
+
volume: Optional[str] = None
|
| 20 |
+
pages: Optional[str] = None
|
| 21 |
+
doi: Optional[str] = None
|
| 22 |
+
|
| 23 |
+
class ReferencesResponse(BaseModel):
|
| 24 |
+
references: List[Reference]
|
| 25 |
+
|
| 26 |
def extract_pdf_text(pdf_file):
|
| 27 |
"""Extrai texto e metadados básicos do PDF"""
|
| 28 |
try:
|
|
|
|
| 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.0-flash-exp', # Modelo Gemini 2.0 Flash
|
| 64 |
+
result_type=ReferencesResponse,
|
| 65 |
+
system_prompt="""
|
| 66 |
+
Você é um especialista em análise de artigos científicos.
|
| 67 |
+
Sua tarefa é identificar e extrair APENAS a seção de referências bibliográficas do texto fornecido.
|
| 68 |
+
|
| 69 |
+
Para cada referência encontrada, extraia:
|
| 70 |
+
- authors: lista completa de autores
|
| 71 |
+
- title: título completo do trabalho
|
| 72 |
+
- journal: nome da revista/conferência/editora
|
| 73 |
+
- year: ano de publicação
|
| 74 |
+
- volume: volume (se disponível)
|
| 75 |
+
- pages: páginas (se disponível)
|
| 76 |
+
- doi: DOI (se disponível)
|
| 77 |
+
|
| 78 |
+
Seja preciso e extraia apenas referências válidas e completas.
|
| 79 |
+
"""
|
| 80 |
+
)
|
| 81 |
|
| 82 |
+
# Limitar o texto para evitar exceder limites da API
|
| 83 |
+
limited_text = text[:15000] # 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}")
|
|
|
|
| 87 |
|
| 88 |
+
# Converter para lista de dicionários para compatibilidade com DataFrame
|
| 89 |
+
references_list = []
|
| 90 |
+
for ref in result.data.references:
|
| 91 |
+
references_list.append({
|
| 92 |
+
"authors": ", ".join(ref.authors) if ref.authors else "",
|
| 93 |
+
"title": ref.title,
|
| 94 |
+
"journal": ref.journal or "",
|
| 95 |
+
"year": ref.year or "",
|
| 96 |
+
"volume": ref.volume or "",
|
| 97 |
+
"pages": ref.pages or "",
|
| 98 |
+
"doi": ref.doi or ""
|
| 99 |
+
})
|
| 100 |
|
| 101 |
+
return references_list
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
except Exception as e:
|
| 104 |
return [{"error": f"Erro ao processar com LLM: {str(e)}"}]
|
|
|
|
| 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("GOOGLE_API_KEY"):
|
| 168 |
+
print("⚠️ AVISO: Chave da API Google não encontrada!")
|
| 169 |
+
print("Crie um arquivo .env com: GOOGLE_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)
|
pyproject.toml
CHANGED
|
@@ -8,7 +8,8 @@ dependencies = [
|
|
| 8 |
"gradio>=4.0.0",
|
| 9 |
"pymupdf>=1.23.0",
|
| 10 |
"pandas>=2.0.0",
|
| 11 |
-
"
|
|
|
|
| 12 |
"python-dotenv>=1.0.0",
|
| 13 |
"pandas-stubs==2.3.2.250827",
|
| 14 |
]
|
|
|
|
| 8 |
"gradio>=4.0.0",
|
| 9 |
"pymupdf>=1.23.0",
|
| 10 |
"pandas>=2.0.0",
|
| 11 |
+
"pydantic-ai>=0.0.14",
|
| 12 |
+
"google-generativeai>=0.8.0",
|
| 13 |
"python-dotenv>=1.0.0",
|
| 14 |
"pandas-stubs==2.3.2.250827",
|
| 15 |
]
|