Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +176 -43
- requirements.txt +8 -1
app.py
CHANGED
|
@@ -1,11 +1,78 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
"""
|
| 7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
def respond(
|
| 11 |
message,
|
|
@@ -15,50 +82,116 @@ def respond(
|
|
| 15 |
temperature,
|
| 16 |
top_p,
|
| 17 |
):
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 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 = message.choices[0].delta.content
|
| 38 |
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
yield response
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
""
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
|
| 63 |
if __name__ == "__main__":
|
| 64 |
-
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
|
| 4 |
+
from langchain_community.vectorstores import FAISS
|
| 5 |
+
from langchain_community.document_loaders import PyPDFLoader, TextLoader, Docx2txtLoader
|
| 6 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 7 |
+
from langchain.chains import RetrievalQA
|
| 8 |
+
from langchain.prompts import PromptTemplate
|
| 9 |
|
| 10 |
+
# Configuración
|
| 11 |
+
API_KEY = os.getenv("GOOGLE_API_KEY") or os.getenv("GEMINI_API_KEY")
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
# Variables globales para RAG
|
| 14 |
+
vectorstore = None
|
| 15 |
+
qa_chain = None
|
| 16 |
+
embeddings = None
|
| 17 |
+
document_sources = []
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def process_documents(files):
|
| 21 |
+
"""Procesa uno o múltiples documentos y crea el vector store"""
|
| 22 |
+
global vectorstore, qa_chain, embeddings, document_sources
|
| 23 |
+
|
| 24 |
+
if not files:
|
| 25 |
+
return "❌ No se subieron archivos"
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
all_docs = []
|
| 29 |
+
processed_files = []
|
| 30 |
+
|
| 31 |
+
# Crear embeddings una sola vez
|
| 32 |
+
if embeddings is None:
|
| 33 |
+
embeddings = GoogleGenerativeAIEmbeddings(
|
| 34 |
+
model="text-embedding-004",
|
| 35 |
+
google_api_key=API_KEY
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Procesar cada archivo
|
| 39 |
+
for file in files:
|
| 40 |
+
file_path = file.name
|
| 41 |
+
ext = file_path.lower().split(".")[-1]
|
| 42 |
+
|
| 43 |
+
# Cargar según tipo
|
| 44 |
+
if ext == "pdf":
|
| 45 |
+
docs = PyPDFLoader(file_path).load()
|
| 46 |
+
elif ext == "docx":
|
| 47 |
+
docs = Docx2txtLoader(file_path).load()
|
| 48 |
+
elif ext == "txt":
|
| 49 |
+
docs = TextLoader(file_path, encoding="utf-8").load()
|
| 50 |
+
else:
|
| 51 |
+
continue # Saltar archivos no soportados
|
| 52 |
+
|
| 53 |
+
all_docs.extend(docs)
|
| 54 |
+
processed_files.append(file_path.split("/")[-1])
|
| 55 |
+
|
| 56 |
+
if not all_docs:
|
| 57 |
+
return "❌ No se pudieron procesar los archivos"
|
| 58 |
+
|
| 59 |
+
# Dividir en chunks
|
| 60 |
+
splitter = RecursiveCharacterTextSplitter(
|
| 61 |
+
chunk_size=800,
|
| 62 |
+
chunk_overlap=120,
|
| 63 |
+
separators=["\n\n", "\n", ". ", " ", ""]
|
| 64 |
+
)
|
| 65 |
+
splits = splitter.split_documents(all_docs)
|
| 66 |
+
|
| 67 |
+
# Crear vector store
|
| 68 |
+
vectorstore = FAISS.from_documents(splits, embeddings)
|
| 69 |
+
document_sources = processed_files
|
| 70 |
+
qa_chain = None # Reset
|
| 71 |
+
|
| 72 |
+
return f"✅ {len(processed_files)} documento(s) procesado(s)\n📊 {len(splits)} chunks creados\n📁 Archivos: {', '.join(processed_files)}"
|
| 73 |
+
|
| 74 |
+
except Exception as e:
|
| 75 |
+
return f"❌ Error: {str(e)}"
|
| 76 |
|
| 77 |
def respond(
|
| 78 |
message,
|
|
|
|
| 82 |
temperature,
|
| 83 |
top_p,
|
| 84 |
):
|
| 85 |
+
global qa_chain, vectorstore
|
| 86 |
+
|
| 87 |
+
if not API_KEY:
|
| 88 |
+
yield "❌ Configura tu GOOGLE_API_KEY o GEMINI_API_KEY"
|
| 89 |
+
return
|
| 90 |
+
|
| 91 |
+
if vectorstore is None:
|
| 92 |
+
yield "❌ Primero sube uno o más documentos usando el botón de arriba"
|
| 93 |
+
return
|
| 94 |
+
|
| 95 |
+
try:
|
| 96 |
+
# Crear QA chain si no existe
|
| 97 |
+
if qa_chain is None:
|
| 98 |
+
llm = ChatGoogleGenerativeAI(
|
| 99 |
+
model="gemini-2.0-flash",
|
| 100 |
+
temperature=temperature,
|
| 101 |
+
google_api_key=API_KEY
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
|
| 105 |
+
|
| 106 |
+
template = f"""{system_message}
|
| 107 |
|
| 108 |
+
Contexto de los documentos:
|
| 109 |
+
{{context}}
|
| 110 |
|
| 111 |
+
Pregunta: {{question}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
Respuesta basada en el contexto:"""
|
| 114 |
+
|
| 115 |
+
prompt = PromptTemplate(
|
| 116 |
+
template=template,
|
| 117 |
+
input_variables=["context", "question"]
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 121 |
+
llm=llm,
|
| 122 |
+
retriever=retriever,
|
| 123 |
+
chain_type="stuff",
|
| 124 |
+
return_source_documents=True,
|
| 125 |
+
chain_type_kwargs={"prompt": prompt}
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
# Generar respuesta
|
| 129 |
+
result = qa_chain.invoke({"query": message})
|
| 130 |
+
response = result["result"]
|
| 131 |
+
|
| 132 |
+
# Agregar fuentes con múltiples documentos
|
| 133 |
+
sources = result.get("source_documents", [])
|
| 134 |
+
if sources:
|
| 135 |
+
response += "\n\n📚 **Fuentes consultadas:**\n"
|
| 136 |
+
for i, doc in enumerate(sources[:4], 1):
|
| 137 |
+
source_file = doc.metadata.get("source", "documento")
|
| 138 |
+
if "/" in source_file:
|
| 139 |
+
source_file = source_file.split("/")[-1]
|
| 140 |
+
page = doc.metadata.get("page", "?")
|
| 141 |
+
snippet = doc.page_content[:120].replace("\n", " ").strip()
|
| 142 |
+
response += f"\n{i}. **{source_file}** (pág. {page}): {snippet}...\n"
|
| 143 |
+
|
| 144 |
yield response
|
| 145 |
+
|
| 146 |
+
except Exception as e:
|
| 147 |
+
yield f"❌ Error: {str(e)}"
|
| 148 |
|
| 149 |
|
| 150 |
+
# Crear interfaz con botón de documentos
|
| 151 |
+
with gr.Blocks(title="RAG Chatbot con Múltiples Documentos") as demo:
|
| 152 |
+
gr.Markdown("# 📁 RAG Chatbot con Múltiples Documentos")
|
| 153 |
+
gr.Markdown("Sube uno o varios documentos (PDF, DOCX, TXT) y hazles preguntas")
|
| 154 |
+
|
| 155 |
+
# Sección de carga de documentos
|
| 156 |
+
with gr.Row():
|
| 157 |
+
files_input = gr.File(
|
| 158 |
+
label="📁 Subir documentos (puedes seleccionar varios)",
|
| 159 |
+
file_count="multiple",
|
| 160 |
+
file_types=[".pdf", ".docx", ".txt"]
|
| 161 |
+
)
|
| 162 |
+
file_status = gr.Textbox(
|
| 163 |
+
label="Estado de los documentos",
|
| 164 |
+
interactive=False,
|
| 165 |
+
max_lines=4
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# Chat interface
|
| 169 |
+
chat_interface = gr.ChatInterface(
|
| 170 |
+
respond,
|
| 171 |
+
additional_inputs=[
|
| 172 |
+
gr.Textbox(
|
| 173 |
+
value="Eres un asistente experto que responde preguntas basándose en los documentos proporcionados. Si no encuentras la información, indica que no está disponible en los documentos.",
|
| 174 |
+
label="Mensaje del sistema"
|
| 175 |
+
),
|
| 176 |
+
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max tokens"),
|
| 177 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.3, step=0.1, label="Temperature"),
|
| 178 |
+
gr.Slider(
|
| 179 |
+
minimum=0.1,
|
| 180 |
+
maximum=1.0,
|
| 181 |
+
value=0.95,
|
| 182 |
+
step=0.05,
|
| 183 |
+
label="Top-p (nucleus sampling)",
|
| 184 |
+
),
|
| 185 |
+
],
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# Conectar evento de carga de archivos
|
| 189 |
+
files_input.change(
|
| 190 |
+
fn=process_documents,
|
| 191 |
+
inputs=[files_input],
|
| 192 |
+
outputs=[file_status]
|
| 193 |
+
)
|
| 194 |
|
| 195 |
|
| 196 |
if __name__ == "__main__":
|
| 197 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
requirements.txt
CHANGED
|
@@ -1 +1,8 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.0.0
|
| 2 |
+
langchain>=0.2.0
|
| 3 |
+
langchain-community>=0.2.0
|
| 4 |
+
langchain-google-genai>=2.0.0
|
| 5 |
+
faiss-cpu>=1.7.4
|
| 6 |
+
pypdf>=4.0.0
|
| 7 |
+
python-docx>=1.0.0
|
| 8 |
+
docx2txt>=0.8
|