Malaji71 commited on
Commit
ff6630f
·
verified ·
1 Parent(s): 4bd0ef6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -25
app.py CHANGED
@@ -1,61 +1,115 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
 
 
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  def respond(
6
  message,
7
  history: list[dict[str, str]],
8
  system_message,
9
- max_tokens,
10
  temperature,
11
  top_p,
12
  hf_token: gr.OAuthToken,
13
  ):
14
- """
15
- 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
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
 
 
 
 
 
 
18
 
19
- messages = [{"role": "system", "content": system_message}]
20
 
 
21
  messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
 
25
  response = ""
26
-
27
- for message in client.chat_completion(
28
  messages,
29
- max_tokens=max_tokens,
30
  stream=True,
31
  temperature=temperature,
32
  top_p=top_p,
33
  ):
34
- choices = message.choices
35
  token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
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
  chatbot = gr.ChatInterface(
47
  respond,
48
  type="messages",
 
 
49
  additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
 
 
 
 
 
 
 
 
 
53
  gr.Slider(
54
  minimum=0.1,
55
  maximum=1.0,
56
  value=0.95,
57
  step=0.05,
58
- label="Top-p (nucleus sampling)",
 
59
  ),
60
  ],
61
  )
@@ -65,6 +119,5 @@ with gr.Blocks() as demo:
65
  gr.LoginButton()
66
  chatbot.render()
67
 
68
-
69
  if __name__ == "__main__":
70
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import faiss
4
+ import pickle
5
+ import numpy as np
6
+ from sentence_transformers import SentenceTransformer
7
+ import os
8
 
9
+ # === CONFIGURACIÓN DEL MODELO Y TOKENS ===
10
+ MODEL_NAME = "openai/gpt-oss-20b"
11
+ MAX_TOKENS = 2048 # máximo permitido por el modelo
12
+
13
+ # === CARGAR FAISS Y DOCUMENTOS (RAG) ===
14
+ print("🔍 Cargando índice FAISS y documentos...")
15
+
16
+ # Rutas relativas (esperamos que estén en la raíz del Space junto con app.py)
17
+ index_path = "nlp_index.faiss"
18
+ docs_path = "nlp_docs.pkl"
19
+
20
+ # Verificar que los archivos existen
21
+ if not os.path.exists(index_path) or not os.path.exists(docs_path):
22
+ raise FileNotFoundError("❌ No se encontraron 'nlp_index.faiss' o 'nlp_docs.pkl' en la raíz del Space.")
23
+
24
+ # Cargar FAISS
25
+ index = faiss.read_index(index_path)
26
+
27
+ # Cargar textos y fuentes
28
+ with open(docs_path, "rb") as f:
29
+ data = pickle.load(f)
30
+ texts = data["texts"]
31
+ sources = data["sources"]
32
+
33
+ embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
34
+ print(f"✅ RAG listo: {index.ntotal} fragmentos cargados.")
35
+
36
+ def retrieve_context(query: str, k: int = 3) -> str:
37
+ """Recupera los k fragmentos más relevantes para la consulta."""
38
+ try:
39
+ query_emb = embedding_model.encode([query], convert_to_numpy=True).astype('float32')
40
+ query_emb = query_emb / np.linalg.norm(query_emb)
41
+ distances, indices = index.search(query_emb, k)
42
+ results = [texts[i] for i in indices[0]]
43
+ return "\n\n".join(results)
44
+ except Exception as e:
45
+ print(f"⚠️ Error en retrieval: {e}")
46
+ return ""
47
 
48
  def respond(
49
  message,
50
  history: list[dict[str, str]],
51
  system_message,
 
52
  temperature,
53
  top_p,
54
  hf_token: gr.OAuthToken,
55
  ):
56
+ # Recuperar contexto relevante
57
+ context = retrieve_context(message)
58
+ if context:
59
+ full_prompt = (
60
+ f"Usa el siguiente contexto para responder de forma precisa y útil:\n\n"
61
+ f"--- CONTEXTO ---\n{context}\n--- FIN DEL CONTEXTO ---\n\n"
62
+ f"Pregunta del usuario:\n{message}"
63
+ )
64
+ else:
65
+ full_prompt = message
66
 
67
+ client = InferenceClient(token=hf_token.token, model=MODEL_NAME)
68
 
69
+ messages = [{"role": "system", "content": system_message}]
70
  messages.extend(history)
71
+ messages.append({"role": "user", "content": full_prompt})
 
72
 
73
  response = ""
74
+ for chunk in client.chat_completion(
 
75
  messages,
76
+ max_tokens=MAX_TOKENS,
77
  stream=True,
78
  temperature=temperature,
79
  top_p=top_p,
80
  ):
 
81
  token = ""
82
+ if chunk.choices and chunk.choices[0].delta.content:
83
+ token = chunk.choices[0].delta.content
 
84
  response += token
85
  yield response
86
 
87
+ # === INTERFAZ EN ESPAÑOL ===
 
 
 
88
  chatbot = gr.ChatInterface(
89
  respond,
90
  type="messages",
91
+ title="🧠 Experimentos NPL Quoota",
92
+ description="Asistente basado en libros de desarrollo personal, liderazgo y psicología cognitiva.",
93
  additional_inputs=[
94
+ gr.Textbox(
95
+ value="Eres un asistente útil, claro y bien informado, especializado en temas de desarrollo personal, liderazgo y comunicación. Responde con precisión y empatía.",
96
+ label="Mensaje del sistema"
97
+ ),
98
+ gr.Slider(
99
+ minimum=0.1,
100
+ maximum=4.0,
101
+ value=0.7,
102
+ step=0.1,
103
+ label="Temperatura",
104
+ info="Controla la creatividad: valores bajos (ej. 0.2) dan respuestas más predecibles y enfocadas; valores altos (ej. 1.2+) dan respuestas más variadas y sorprendentes."
105
+ ),
106
  gr.Slider(
107
  minimum=0.1,
108
  maximum=1.0,
109
  value=0.95,
110
  step=0.05,
111
+ label="Top-p (muestreo nuclear)",
112
+ info="Filtra las opciones menos probables. 0.95 es un buen equilibrio entre diversidad y coherencia."
113
  ),
114
  ],
115
  )
 
119
  gr.LoginButton()
120
  chatbot.render()
121
 
 
122
  if __name__ == "__main__":
123
+ demo.launch()