Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,132 @@
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
6 |
-
"""
|
7 |
client = InferenceClient("google/gemma-3-27b-it")
|
|
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
def respond(
|
11 |
-
message,
|
12 |
-
history:
|
13 |
-
system_message,
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
|
|
17 |
):
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
if val[0]:
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
|
26 |
-
|
27 |
|
28 |
-
|
29 |
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
messages,
|
32 |
max_tokens=max_tokens,
|
33 |
stream=True,
|
34 |
temperature=temperature,
|
35 |
top_p=top_p,
|
36 |
):
|
37 |
-
token =
|
38 |
-
|
39 |
response += token
|
40 |
yield response
|
41 |
|
42 |
-
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
demo = gr.ChatInterface(
|
47 |
respond,
|
48 |
additional_inputs=[
|
49 |
-
gr.Textbox(value="
|
|
|
50 |
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
|
54 |
-
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
],
|
|
|
|
|
60 |
)
|
61 |
|
62 |
-
|
63 |
if __name__ == "__main__":
|
64 |
-
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
3 |
+
import PyPDF2
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
import numpy as np
|
6 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
7 |
+
import os
|
8 |
+
from typing import List, Tuple
|
9 |
|
10 |
+
# Inicialização do cliente de inferência e modelo de embeddings
|
|
|
|
|
11 |
client = InferenceClient("google/gemma-3-27b-it")
|
12 |
+
embedder = SentenceTransformer('all-MiniLM-L6-v2')
|
13 |
|
14 |
+
# Classe para gerenciar o conhecimento dos PDFs
|
15 |
+
class PDFKnowledgeBase:
|
16 |
+
def __init__(self):
|
17 |
+
self.documents = []
|
18 |
+
self.embeddings = None
|
19 |
+
|
20 |
+
def load_pdfs(self, pdf_directory: str):
|
21 |
+
"""Carrega todos os PDFs de um diretório"""
|
22 |
+
self.documents = []
|
23 |
+
for filename in os.listdir(pdf_directory):
|
24 |
+
if filename.endswith('.pdf'):
|
25 |
+
pdf_path = os.path.join(pdf_directory, filename)
|
26 |
+
with open(pdf_path, 'rb') as file:
|
27 |
+
pdf_reader = PyPDF2.PdfReader(file)
|
28 |
+
text = ""
|
29 |
+
for page in pdf_reader.pages:
|
30 |
+
text += page.extract_text() + "\n"
|
31 |
+
self.documents.append({
|
32 |
+
'filename': filename,
|
33 |
+
'content': text
|
34 |
+
})
|
35 |
+
|
36 |
+
# Gera embeddings para todos os documentos
|
37 |
+
contents = [doc['content'] for doc in self.documents]
|
38 |
+
self.embeddings = embedder.encode(contents, convert_to_numpy=True)
|
39 |
+
|
40 |
+
def get_relevant_context(self, query: str, k: int = 3) -> str:
|
41 |
+
"""Recupera os k documentos mais relevantes para a query"""
|
42 |
+
if self.embeddings is None or len(self.documents) == 0:
|
43 |
+
return "Nenhum documento carregado ainda."
|
44 |
+
|
45 |
+
query_embedding = embedder.encode(query, convert_to_numpy=True)
|
46 |
+
similarities = cosine_similarity([query_embedding], self.embeddings)[0]
|
47 |
+
|
48 |
+
# Obtém os índices dos k documentos mais similares
|
49 |
+
top_k_indices = np.argsort(similarities)[-k:][::-1]
|
50 |
+
|
51 |
+
# Constrói o contexto relevante
|
52 |
+
context = ""
|
53 |
+
for idx in top_k_indices:
|
54 |
+
context += f"Documento: {self.documents[idx]['filename']}\n"
|
55 |
+
context += f"Trecho: {self.documents[idx]['content'][:500]}...\n\n"
|
56 |
+
|
57 |
+
return context
|
58 |
+
|
59 |
+
# Inicializa a base de conhecimento
|
60 |
+
knowledge_base = PDFKnowledgeBase()
|
61 |
|
62 |
def respond(
|
63 |
+
message: str,
|
64 |
+
history: List[Tuple[str, str]],
|
65 |
+
system_message: str,
|
66 |
+
max_tokens: int,
|
67 |
+
temperature: float,
|
68 |
+
top_p: float,
|
69 |
+
pdf_directory: str
|
70 |
):
|
71 |
+
# Carrega os PDFs se ainda não foram carregados
|
72 |
+
if not knowledge_base.documents:
|
73 |
+
knowledge_base.load_pdfs(pdf_directory)
|
74 |
+
|
75 |
+
# Obtém contexto relevante da base de conhecimento
|
76 |
+
context = knowledge_base.get_relevant_context(message)
|
77 |
+
|
78 |
+
# Constrói o prompt com o contexto RAG
|
79 |
+
rag_prompt = f"""Você é Grok 3, criado por xAI. Use o seguinte contexto dos documentos para responder à pergunta:
|
80 |
|
81 |
+
{context}
|
|
|
|
|
|
|
|
|
82 |
|
83 |
+
Pergunta do usuário: {message}
|
84 |
|
85 |
+
Responda de forma clara e precisa, utilizando o contexto quando relevante."""
|
86 |
|
87 |
+
messages = [
|
88 |
+
{"role": "system", "content": system_message},
|
89 |
+
{"role": "user", "content": rag_prompt}
|
90 |
+
]
|
91 |
+
|
92 |
+
# Adiciona histórico se existir
|
93 |
+
for user_msg, assistant_msg in history:
|
94 |
+
if user_msg:
|
95 |
+
messages.append({"role": "user", "content": user_msg})
|
96 |
+
if assistant_msg:
|
97 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
98 |
+
|
99 |
+
response = ""
|
100 |
+
for message_chunk in client.chat_completion(
|
101 |
messages,
|
102 |
max_tokens=max_tokens,
|
103 |
stream=True,
|
104 |
temperature=temperature,
|
105 |
top_p=top_p,
|
106 |
):
|
107 |
+
token = message_chunk.choices[0].delta.content
|
|
|
108 |
response += token
|
109 |
yield response
|
110 |
|
111 |
+
# Interface do Gradio
|
|
|
|
|
|
|
112 |
demo = gr.ChatInterface(
|
113 |
respond,
|
114 |
additional_inputs=[
|
115 |
+
gr.Textbox(value="Você é um assistente útil que responde com base em documentos PDF.",
|
116 |
+
label="System message"),
|
117 |
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
118 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
119 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05,
|
120 |
+
label="Top-p (nucleus sampling)"),
|
121 |
+
gr.Textbox(value="./pdfs", label="Diretório dos PDFs"),
|
|
|
|
|
|
|
|
|
122 |
],
|
123 |
+
title="RAG Chatbot com PDFs",
|
124 |
+
description="Faça perguntas e obtenha respostas baseadas em documentos PDF carregados."
|
125 |
)
|
126 |
|
|
|
127 |
if __name__ == "__main__":
|
128 |
+
# Crie um diretório 'pdfs' e coloque seus PDFs lá
|
129 |
+
if not os.path.exists("./pdfs"):
|
130 |
+
os.makedirs("./pdfs")
|
131 |
+
|
132 |
+
demo.launch()
|