pdf-transcript / pdf-gardio.py
vicmanmkt's picture
Create pdf-gardio.py
61ecfd9 verified
Raw History Blame Contribute Delete
9.47 kB
import os
import fitz # PyMuPDF
from pathlib import Path
import gradio as gr
import google.generativeai as genai
import time
import tempfile
from PIL import Image
class PDFTranscriberGradio:
def __init__(self):
self.temp_files = []
def get_selected_model(self, model_choice):
"""Retorna o ID do modelo selecionado"""
return model_choice.split(" - ")[0].strip()
def convert_pdf_page_to_image(self, pdf_document, page_number):
"""Converte uma página do PDF em imagem e salva temporariamente"""
page = pdf_document[page_number]
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
img_data = pix.tobytes("png")
# Criar arquivo temporário com nome único baseado no timestamp
temp_filename = f'page_{page_number}_{int(time.time()*1000)}.png'
temp_path = os.path.join(tempfile.gettempdir(), temp_filename)
with open(temp_path, 'wb') as temp_file:
temp_file.write(img_data)
# Adicionar à lista de arquivos temporários
self.temp_files.append(temp_path)
return temp_path
def analyze_page_with_gemini(self, image_path, page_num, model_name, temperature, top_p, top_k):
"""Analisa uma página usando o modelo Gemini selecionado"""
try:
# Carregar a imagem
img = Image.open(image_path)
# Configurar o modelo Gemini
model = genai.GenerativeModel(model_name)
# Criar prompt
prompt = """Analise esta página do documento em detalhes. Por favor, inclua:
1. Conteúdo textual e sua organização
2. Layout e estrutura visual
3. Elementos gráficos, tabelas ou imagens
4. Informações importantes ou destaques
5. Formatação e estilo do documento"""
# Gerar resposta
response = model.generate_content([prompt, img], generation_config={
'temperature': temperature,
'max_output_tokens': 4096,
'top_p': top_p,
'top_k': int(top_k),
})
# Fechar a imagem explicitamente
img.close()
return response.text
except Exception as e:
return f"Erro ao analisar página {page_num}: {str(e)}"
def cleanup_temp_files(self):
"""Limpa todos os arquivos temporários"""
for temp_file in self.temp_files:
try:
if os.path.exists(temp_file):
# Tentar várias vezes em caso de arquivo em uso
for _ in range(3):
try:
os.unlink(temp_file)
break
except PermissionError:
time.sleep(0.5)
except Exception as e:
print(f"Aviso: Não foi possível remover arquivo temporário {temp_file}: {e}")
self.temp_files = []
def extract_text_from_pdf(self, pdf_path):
try:
doc = fitz.open(pdf_path)
text = ""
for page in doc:
text += page.get_text()
return text
except Exception as e:
raise Exception(f"Erro ao extrair texto do PDF: {str(e)}")
def process_pdf(self, pdf_file, api_key, model_choice, temperature, top_p, top_k):
status_updates = ["Iniciando processamento..."]
yield "\n".join(status_updates), None, None
try:
# Verificar se o arquivo foi fornecido
if pdf_file is None:
raise Exception("Nenhum arquivo enviado")
# Configurar API Gemini
if not api_key or api_key.strip() == "":
raise Exception("API Key não fornecida")
genai.configure(api_key=api_key)
# Obter o modelo selecionado
model_name = self.get_selected_model(model_choice)
# Abrir o PDF
# Gradio retorna um objeto NamedString, precisamos usar o caminho do arquivo
doc = fitz.open(pdf_file.name)
# Extrair texto tradicional
status_updates.append("Extraindo texto do PDF...")
yield "\n".join(status_updates), None, None
text_content = ""
for page in doc:
text_content += page.get_text()
# Analisar cada página como imagem
status_updates.append("Analisando páginas como imagens...")
yield "\n".join(status_updates), None, None
page_analyses = []
for page_num in range(len(doc)):
status_updates.append(f"Processando página {page_num + 1} de {len(doc)}...")
yield "\n".join(status_updates), None, None
image_path = self.convert_pdf_page_to_image(doc, page_num)
analysis = self.analyze_page_with_gemini(
image_path,
page_num + 1,
model_name,
temperature,
top_p,
top_k
)
page_analyses.append(f"\n=== Análise da Página {page_num + 1} ===\n{analysis}")
# Combinar resultados
final_output = "=== CONTEÚDO TEXTUAL ===\n\n"
final_output += text_content
final_output += "\n\n=== ANÁLISE VISUAL DAS PÁGINAS ===\n"
final_output += "\n".join(page_analyses)
# Gerar nome para arquivo de saída
output_filename = f"analise_pdf_{int(time.time())}.txt"
output_path = os.path.join(tempfile.gettempdir(), output_filename)
# Salvar resultado
with open(output_path, 'w', encoding='utf-8') as f:
f.write(final_output)
status_updates.append(f"Análise completa! Arquivo salvo temporariamente.")
# Retornar o conteúdo e o caminho do arquivo para download
yield "\n".join(status_updates), final_output, output_path
except Exception as e:
error_msg = f"Erro: {str(e)}"
status_updates.append(error_msg)
yield "\n".join(status_updates), None, None
finally:
# Limpar arquivos temporários
self.cleanup_temp_files()
def create_interface(self):
with gr.Blocks(title="Transcritor de PDF com Gemini API") as interface:
gr.Markdown("# Transcritor de PDF com Gemini API")
with gr.Row():
with gr.Column():
api_key = gr.Textbox(label="API Key Gemini", type="password")
pdf_file = gr.File(label="Arquivo PDF", file_types=[".pdf"])
with gr.Row():
model_choice = gr.Dropdown(
label="Modelo",
choices=[
"gemini-2.0-flash-exp - Última geração (Experimental)",
"gemini-1.5-flash - Rápido e versátil",
"gemini-1.5-flash-8b - Alto volume",
"gemini-1.5-pro - Raciocínio complexo"
],
value="gemini-1.5-pro - Raciocínio complexo"
)
with gr.Row():
temperature = gr.Slider(
label="Temperatura",
minimum=0.0,
maximum=1.0,
step=0.1,
value=0.4
)
with gr.Row():
top_p = gr.Slider(
label="Top P",
minimum=0.0,
maximum=1.0,
step=0.1,
value=0.8
)
top_k = gr.Slider(
label="Top K",
minimum=1,
maximum=40,
step=1,
value=32
)
process_button = gr.Button("Transcrever e Analisar")
with gr.Column():
status_output = gr.Textbox(label="Status", lines=10)
result_output = gr.Textbox(label="Resultado", lines=20)
file_output = gr.File(label="Download do Resultado")
process_button.click(
fn=self.process_pdf,
inputs=[pdf_file, api_key, model_choice, temperature, top_p, top_k],
outputs=[status_output, result_output, file_output],
show_progress=True
)
return interface
def run(self):
interface = self.create_interface()
interface.launch()
if __name__ == "__main__":
app = PDFTranscriberGradio()
app.run()