Darkka commited on
Commit
34f3efd
路
verified 路
1 Parent(s): 54467ee

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -0
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from langchain_community.document_loaders import TextLoader
3
+ from langchain_text_splitters import CharacterTextSplitter
4
+ from langchain_community.embeddings import HuggingFaceEmbeddings
5
+ from langchain_community.vectorstores import FAISS
6
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
7
+ import torch
8
+ import os
9
+
10
+ # --- 0. CONFIGURACI脫N INICIAL Y PREVENCI脫N DE ERRORES ---
11
+ # Define la carpeta temporal para guardar los embeddings y la configuraci贸n
12
+ os.environ['HF_HOME'] = '/tmp/hf_cache'
13
+
14
+ # --- A. BASE DE DATOS Y RAG (Su antigua Celda 2) ---
15
+
16
+ def initialize_database():
17
+ """Carga documentos, divide y crea la base de datos vectorial FAISS."""
18
+ # 1. Definir la Base de Conocimiento (Corpus)
19
+ datos_conocimiento = """
20
+ Historia de la IA en Chile:
21
+ El desarrollo de la Inteligencia Artificial en Chile comenz贸 formalmente en la d茅cada de 1970, con foco en el 谩rea de optimizaci贸n de recursos.
22
+ El centro principal de investigaci贸n es la Pontificia Universidad Cat贸lica (PUC) y la Universidad de Chile.
23
+ La especialidad m谩s popular en el pa铆s es el Procesamiento de Lenguaje Natural (NLP), debido a la gran cantidad de texto disponible en espa帽ol.
24
+ En 2023, el gobierno chileno lanz贸 un plan nacional de IA con el objetivo de fomentar la inversi贸n privada y la educaci贸n.
25
+ La IA se utiliza principalmente en miner铆a, finanzas y agricultura.
26
+ """
27
+ nombre_archivo = "conocimiento_chile.txt"
28
+ with open(nombre_archivo, "w", encoding="utf-8") as f:
29
+ f.write(datos_conocimiento)
30
+
31
+ # 2. Cargar y Dividir el Documento
32
+ loader = TextLoader(nombre_archivo, encoding="utf-8")
33
+ documentos = loader.load()
34
+ text_splitter = CharacterTextSplitter(separator="\n", chunk_size=150, chunk_overlap=0)
35
+ documentos_divididos = text_splitter.split_documents(documentos)
36
+
37
+ # 3. Crear Embeddings y Vector Store
38
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
39
+ db = FAISS.from_documents(documentos_divididos, embeddings)
40
+ return db
41
+
42
+ # Inicializar la base de datos al inicio del script
43
+ db = initialize_database()
44
+
45
+
46
+ # --- B. CONFIGURACI脫N DEL LLM GRANDE (Soluci贸n al Error de Memoria) ---
47
+
48
+ # Configuraci贸n para cargar el modelo en 4 bits (ESENCIAL para ahorrar VRAM)
49
+ quant_config = BitsAndBytesConfig(
50
+ load_in_4bit=True,
51
+ bnb_4bit_quant_type="nf4",
52
+ bnb_4bit_compute_dtype=torch.bfloat16
53
+ )
54
+
55
+ model_name = "mistralai/Mistral-7B-Instruct-v0.2"
56
+
57
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
58
+ model = AutoModelForCausalLM.from_pretrained(
59
+ model_name,
60
+ quantization_config=quant_config,
61
+ device_map="auto" # Mapea autom谩ticamente a la GPU
62
+ )
63
+
64
+ pipe = pipeline(
65
+ "text-generation",
66
+ model=model,
67
+ tokenizer=tokenizer,
68
+ max_new_tokens=256,
69
+ )
70
+
71
+ # --- C. PROMPT Y FUNCI脫N RAG (Implementaci贸n de la Persona) ---
72
+
73
+ prompt_template_persona = """[INST] Eres un asistente experto en ciencia de datos y aprendizaje profundo, con un vocabulario formal y un tono cort茅s y servicial. Tu objetivo principal es ser preciso y conciso.
74
+
75
+ [REGLAS]
76
+ 1. Usa la siguiente informaci贸n de contexto para responder la pregunta al final.
77
+ 2. Si no puedes encontrar la respuesta en el contexto, simplemente responde "No tengo informaci贸n sobre ese tema espec铆fico en mi base de datos de conocimiento."
78
+
79
+ Contexto:
80
+ {context}
81
+
82
+ Pregunta: {question} [/INST]"""
83
+
84
+
85
+ def rag_chain_manual(query, db, llm_pipeline, prompt_template):
86
+ # 1. Retrieval
87
+ docs = db.similarity_search(query, k=2)
88
+ context = "\n\n---\n\n".join([doc.page_content for doc in docs])
89
+
90
+ # 2. Augmentation
91
+ final_prompt = prompt_template.format(context=context, question=query)
92
+
93
+ # 3. Generation
94
+ result = llm_pipeline(final_prompt)
95
+
96
+ # 4. Extracci贸n y Limpieza
97
+ generated_text = result[0]['generated_text']
98
+
99
+ # Limpiamos la respuesta
100
+ try:
101
+ final_answer = generated_text.split("[/INST]")[-1].strip()
102
+ except:
103
+ final_answer = generated_text.strip()
104
+
105
+ # Devolvemos la respuesta para la interfaz de Gradio
106
+ return final_answer
107
+
108
+
109
+ # --- D. INTERFAZ GRADI (La Conversaci贸n Final) ---
110
+
111
+ # Funci贸n que Gradio usar谩 para procesar la pregunta
112
+ def responder_consulta(query):
113
+ # Llamamos a nuestra funci贸n RAG principal
114
+ respuesta = rag_chain_manual(query, db, pipe, prompt_template_persona)
115
+ return respuesta
116
+
117
+ # Crear la interfaz de usuario simple con Gradio
118
+ demo = gr.Interface(
119
+ fn=responder_consulta,
120
+ inputs=gr.Textbox(label="Ingrese su pregunta para la IA experta:"),
121
+ outputs="text",
122
+ title="Asistente RAG Experto (Mistral-7B)",
123
+ description="Sistema de Generaci贸n Aumentada por Recuperaci贸n (RAG) para consultas sobre IA en Chile.",
124
+ allow_flagging="never"
125
+ )
126
+
127
+ # Iniciar la interfaz (esto es lo que ejecuta el Space)
128
+ if __name__ == "__main__":
129
+ demo.launch()