Download app.py from Darkk-IA/README: direct link, hf CLI and curl.
- Browser
- Download file 3.28 kB
-
https://huggingface.co/spaces/Darkk-IA/README/resolve/main/app.py
- Command line
-
hf download hf://spaces/Darkk-IA/README/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Darkk-IA/README/resolve/main/app.py
3.28 kB
| import gradio as gr | |
| from langchain_community.document_loaders import TextLoader | |
| from langchain_text_splitters import CharacterTextSplitter | |
| from langchain_community.embeddings import HuggingFaceEmbeddings | |
| from langchain_community.vectorstores import FAISS | |
| from huggingface_hub import InferenceClient | |
| import os | |
| # --- 1. CONFIGURACIÓN DE LA BASE DE DATOS (RAG) --- | |
| def initialize_database(): | |
| # Datos sobre IA en Chile | |
| datos_conocimiento = """ | |
| Historia de la IA en Chile: | |
| 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. | |
| El centro principal de investigación es la Pontificia Universidad Católica (PUC) y la Universidad de Chile. | |
| 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. | |
| En 2023, el gobierno chileno lanzó un plan nacional de IA con el objetivo de fomentar la inversión privada y la educación. | |
| La IA se utiliza principalmente en minería, finanzas y agricultura. | |
| """ | |
| # Crear archivo y cargar | |
| nombre_archivo = "conocimiento_chile.txt" | |
| with open(nombre_archivo, "w", encoding="utf-8") as f: | |
| f.write(datos_conocimiento) | |
| loader = TextLoader(nombre_archivo, encoding="utf-8") | |
| documentos = loader.load() | |
| # Dividir texto | |
| text_splitter = CharacterTextSplitter(separator="\n", chunk_size=150, chunk_overlap=0) | |
| documentos_divididos = text_splitter.split_documents(documentos) | |
| # Crear base de datos (Embeddings) | |
| embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2") | |
| db = FAISS.from_documents(documentos_divididos, embeddings) | |
| return db | |
| # Inicializar DB | |
| db = initialize_database() | |
| # --- 2. CONEXIÓN RÁPIDA (API) --- | |
| token_secreto = os.getenv("HF_TOKEN") | |
| client = InferenceClient( | |
| "mistralai/Mistral-7B-Instruct-v0.2", | |
| token=token_secreto | |
| ) | |
| # --- 3. LÓGICA DE RESPUESTA --- | |
| def responder(message, history): | |
| # A. Buscar contexto | |
| docs = db.similarity_search(message, k=2) | |
| context = "\n".join([doc.page_content for doc in docs]) | |
| # B. Instrucción de Personalidad | |
| system_prompt = f"""[INST] Actúa como 'Alex', un experto en IA chilena, amable y curioso. | |
| Usa este CONTEXTO para responder si es útil: | |
| {context} | |
| Si la pregunta no tiene que ver con el contexto, responde con tu conocimiento general. Sé conciso. | |
| Pregunta: {message} [/INST]""" | |
| # C. Generación rápida | |
| response = "" | |
| try: | |
| for token in client.chat_completion(messages=[{"role": "user", "content": system_prompt}], max_tokens=512, stream=True): | |
| if token.choices[0].delta.content: | |
| response += token.choices[0].delta.content | |
| yield response | |
| except Exception as e: | |
| yield f"Error: Verifica que tu HF_TOKEN esté bien puesto en Settings. Detalles: {str(e)}" | |
| # --- 4. INTERFAZ --- | |
| demo = gr.ChatInterface( | |
| fn=responder, | |
| title="Chat con Alex (Modo API)", | |
| description="Pregúntame sobre la IA en Chile.", | |
| examples=["¿Qué es la IA en Chile?", "¿Quién ganó el mundial?"] | |
| # HE ELIMINADO LA LÍNEA 'theme' QUE DABA ERROR | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |