Spaces:
Sleeping
Sleeping
File size: 2,889 Bytes
f16c594 0503087 5624aa2 bbcd85b 0503087 34e5d9c 5624aa2 bbcd85b 5624aa2 34e5d9c bbcd85b 34e5d9c bbcd85b f16c594 34e5d9c 7398145 5624aa2 34e5d9c 71c21c0 34e5d9c 5624aa2 f16c594 13ae474 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import fitz # PyMuPDF
import traceback
# Carregar o tokenizer e o modelo
tokenizer = AutoTokenizer.from_pretrained("Locutusque/gpt2-xl-conversational")
model = AutoModelForCausalLM.from_pretrained("Locutusque/gpt2-xl-conversational")
# Variável global para armazenar o conteúdo do PDF
pdf_content = ""
# Função para ler o PDF
def read_pdf(file_path):
try:
doc = fitz.open(file_path)
text = ""
for page_num in range(len(doc)):
page = doc.load_page(page_num)
text += page.get_text()
return text
except Exception as e:
print(f"Erro ao ler o PDF: {e}")
print(traceback.format_exc())
return ""
# Função para carregar o PDF e armazenar o conteúdo
def load_pdf(pdf_file):
global pdf_content
try:
pdf_path = pdf_file.name # Acessar o caminho do arquivo carregado
pdf_content = read_pdf(pdf_path)
if pdf_content:
return "PDF carregado com sucesso!"
else:
return "Falha ao carregar o PDF."
except Exception as e:
print(f"Erro ao carregar o PDF: {e}")
print(traceback.format_exc())
return "Erro ao carregar o PDF."
# Função para responder perguntas com base no conteúdo do PDF
def answer_question(question, max_length=200, temperature=0.7, top_k=50, top_p=0.95):
global pdf_content
try:
if not pdf_content:
return "Por favor, carregue um PDF primeiro.", ""
prompt = f"Conteúdo do PDF: {pdf_content}\nPergunta: {question}\nResposta em português:"
print(f"Prompt: {prompt}") # Adicionar log para depuração
inputs = tokenizer(prompt, return_tensors="pt")
outputs = model.generate(
inputs.input_ids,
max_length=max_length,
temperature=temperature,
top_k=top_k,
top_p=top_p,
num_return_sequences=1
)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
return response, prompt
except Exception as e:
print(f"Erro ao gerar resposta: {e}")
print(traceback.format_exc())
return "Erro ao gerar resposta.", prompt
# Interface do Gradio para carregar PDF e fazer perguntas
pdf_loader = gr.Interface(
fn=load_pdf,
inputs=gr.File(label="Carregue um PDF"),
outputs="text",
title="Carregar PDF"
)
question_answerer = gr.Interface(
fn=answer_question,
inputs=gr.Textbox(lines=2, label="Pergunta"),
outputs=[gr.Textbox(label="Resposta"), gr.Textbox(label="Prompt usado")],
title="Perguntas sobre o PDF"
)
# Combinar as interfaces em uma aplicação
iface = gr.TabbedInterface(
[pdf_loader, question_answerer],
["Carregar PDF", "Fazer Perguntas"]
)
if __name__ == "__main__":
iface.launch() |