Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,68 @@
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
|
26 |
-
|
27 |
|
28 |
-
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
|
39 |
-
|
40 |
-
|
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="You are a friendly Chatbot.", label="System message"),
|
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 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
-
)
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
import os
|
3 |
+
import pickle
|
4 |
+
import numpy as np
|
5 |
+
import faiss
|
6 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
7 |
+
import torch
|
8 |
+
from sentence_transformers import SentenceTransformer
|
9 |
|
10 |
+
# Carga del índice FAISS y los chunks de texto
|
11 |
+
with open("index.pkl", "rb") as f:
|
12 |
+
index, chunks = pickle.load(f)
|
|
|
13 |
|
14 |
+
# Modelo de embeddings (debe coincidir con el usado en indexador.py)
|
15 |
+
embedder = SentenceTransformer("jinaai/jina-embeddings-v2-base-es")
|
16 |
|
17 |
+
# Modelo LLM (LLaMA o similar)
|
18 |
+
llm = pipeline(
|
19 |
+
"text-generation",
|
20 |
+
model="meta-llama/Llama-3.2-3B-Instruct",
|
21 |
+
device_map="auto",
|
22 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
23 |
+
token=os.getenv("HF_KEY"),
|
24 |
+
trust_remote_code=True
|
25 |
+
)
|
26 |
|
27 |
+
def responder(pregunta):
|
28 |
+
pregunta_embedding = embedder.encode([pregunta])
|
29 |
+
_, indices = index.search(np.array(pregunta_embedding).reshape(1, -1), k=50)
|
30 |
+
result_chunks = [chunks[i] for i in indices[0]]
|
|
|
31 |
|
32 |
+
contexto_final = "\n\n".join(result_chunks[:3])
|
33 |
|
34 |
+
prompt = f"""
|
35 |
+
Actúa como un asesor legal colombiano, especializado en el Código de Tránsito, Código de Policía y Código Penal.
|
36 |
+
Tu tarea es analizar el siguiente contexto legal y responder la pregunta de forma clara, completa y profesional.
|
37 |
|
38 |
+
Instrucciones:
|
39 |
+
- Usa un lenguaje formal y comprensible.
|
40 |
+
- Cita artículos o sanciones si están presentes en el contexto.
|
41 |
+
- No inventes leyes que no están en el texto.
|
42 |
+
- Si no hay suficiente contexto, responde:
|
43 |
+
"No encontré información suficiente en la ley para responder a esta pregunta."
|
|
|
|
|
44 |
|
45 |
+
Contexto legal:
|
46 |
+
{contexto_final}
|
47 |
|
48 |
+
Pregunta:
|
49 |
+
{pregunta}
|
50 |
|
51 |
+
Respuesta:
|
52 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
+
output = llm(prompt, max_new_tokens=400, temperature=0.4)[0]["generated_text"]
|
55 |
+
|
56 |
+
return output.split("Respuesta:")[-1].strip() if "Respuesta:" in output else output.strip()
|
57 |
+
|
58 |
+
# Interfaz Gradio
|
59 |
+
demo = gr.Interface(
|
60 |
+
fn=responder,
|
61 |
+
inputs=gr.Textbox(lines=2, placeholder="Ej: ¿Qué pasa si cometo homicidio?", label="Escribe tu pregunta"),
|
62 |
+
outputs=gr.Textbox(label="Respuesta generada"),
|
63 |
+
title="Asistente Legal Colombiano",
|
64 |
+
description="Consulta el Código de Tránsito, Código de Policía y Código Penal colombiano.",
|
65 |
+
theme="default"
|
66 |
+
)
|
67 |
|
68 |
+
demo.launch()
|
|