Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""app"""
|
| 3 |
|
|
@@ -14,7 +16,7 @@ import tempfile
|
|
| 14 |
import numpy as np
|
| 15 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 16 |
|
| 17 |
-
#
|
| 18 |
load_dotenv()
|
| 19 |
OPENROUTER_API_KEY = os.getenv("ROUTER_API_KEY")
|
| 20 |
|
|
@@ -26,7 +28,7 @@ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-b
|
|
| 26 |
qa_chain = None
|
| 27 |
processed_file = None
|
| 28 |
|
| 29 |
-
#
|
| 30 |
def load_default_pdf():
|
| 31 |
global qa_chain, processed_file
|
| 32 |
try:
|
|
@@ -65,6 +67,7 @@ def calculate_rag_metrics(query, response, source_docs):
|
|
| 65 |
[query_embedding], [response_embedding]
|
| 66 |
)[0][0]
|
| 67 |
|
|
|
|
| 68 |
doc_similarities = []
|
| 69 |
for doc in source_docs:
|
| 70 |
doc_embedding = embeddings.embed_query(doc.page_content[:1000])
|
|
@@ -119,7 +122,7 @@ def ask_question(question):
|
|
| 119 |
global qa_chain
|
| 120 |
|
| 121 |
if qa_chain is None:
|
| 122 |
-
return "⚠️ Por favor, carregue um PDF primeiro", "",
|
| 123 |
|
| 124 |
try:
|
| 125 |
system_prompt = (
|
|
@@ -152,15 +155,14 @@ def ask_question(question):
|
|
| 152 |
resposta['source_documents']
|
| 153 |
)
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
)
|
| 159 |
|
| 160 |
return resposta['result'], sources, metrics_text
|
| 161 |
|
| 162 |
except Exception as e:
|
| 163 |
-
return f"❌ Erro ao processar pergunta: {str(e)}", "",
|
| 164 |
|
| 165 |
# Interface Gradio
|
| 166 |
with gr.Blocks(title="Chat com PDF usando RAG", theme=gr.themes.Soft()) as demo:
|
|
@@ -195,9 +197,10 @@ with gr.Blocks(title="Chat com PDF usando RAG", theme=gr.themes.Soft()) as demo:
|
|
| 195 |
outputs=[answer_output, sources_output, metrics_output]
|
| 196 |
)
|
| 197 |
|
| 198 |
-
#
|
| 199 |
load_default_pdf()
|
| 200 |
|
| 201 |
# Compartilhamento opcional
|
| 202 |
share = True if 'COLAB_JUPYTER_TRANSPORT' in os.environ else False
|
| 203 |
demo.launch(share=share, debug=False)
|
|
|
|
|
|
| 1 |
+
# Autor: Luan Alysson de Souza
|
| 2 |
+
|
| 3 |
# -*- coding: utf-8 -*-
|
| 4 |
"""app"""
|
| 5 |
|
|
|
|
| 16 |
import numpy as np
|
| 17 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 18 |
|
| 19 |
+
# Carrega variáveis de ambiente
|
| 20 |
load_dotenv()
|
| 21 |
OPENROUTER_API_KEY = os.getenv("ROUTER_API_KEY")
|
| 22 |
|
|
|
|
| 28 |
qa_chain = None
|
| 29 |
processed_file = None
|
| 30 |
|
| 31 |
+
# Carrega o PDF fixo automaticamente
|
| 32 |
def load_default_pdf():
|
| 33 |
global qa_chain, processed_file
|
| 34 |
try:
|
|
|
|
| 67 |
[query_embedding], [response_embedding]
|
| 68 |
)[0][0]
|
| 69 |
|
| 70 |
+
# Mantido apenas para fins internos, mas não será exibido
|
| 71 |
doc_similarities = []
|
| 72 |
for doc in source_docs:
|
| 73 |
doc_embedding = embeddings.embed_query(doc.page_content[:1000])
|
|
|
|
| 122 |
global qa_chain
|
| 123 |
|
| 124 |
if qa_chain is None:
|
| 125 |
+
return "⚠️ Por favor, carregue um PDF primeiro", "", ""
|
| 126 |
|
| 127 |
try:
|
| 128 |
system_prompt = (
|
|
|
|
| 155 |
resposta['source_documents']
|
| 156 |
)
|
| 157 |
|
| 158 |
+
# Exibe apenas o nível de confiança
|
| 159 |
+
confidence = metrics.get("query_response_similarity", 0)
|
| 160 |
+
metrics_text = f"🔎 Nível de Confiança da Resposta: {confidence:.2f}"
|
|
|
|
| 161 |
|
| 162 |
return resposta['result'], sources, metrics_text
|
| 163 |
|
| 164 |
except Exception as e:
|
| 165 |
+
return f"❌ Erro ao processar pergunta: {str(e)}", "", ""
|
| 166 |
|
| 167 |
# Interface Gradio
|
| 168 |
with gr.Blocks(title="Chat com PDF usando RAG", theme=gr.themes.Soft()) as demo:
|
|
|
|
| 197 |
outputs=[answer_output, sources_output, metrics_output]
|
| 198 |
)
|
| 199 |
|
| 200 |
+
# Carrega o PDF fixo ao iniciar
|
| 201 |
load_default_pdf()
|
| 202 |
|
| 203 |
# Compartilhamento opcional
|
| 204 |
share = True if 'COLAB_JUPYTER_TRANSPORT' in os.environ else False
|
| 205 |
demo.launch(share=share, debug=False)
|
| 206 |
+
|