File size: 4,371 Bytes
cc39422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import gradio as gr
import pandas as pd
from PyPDF2 import PdfReader
import torch
from transformers import BertForQuestionAnswering, BertTokenizer, pipeline
from sentence_transformers import SentenceTransformer, util

# Configuraci贸n inicial
model_name = 'dccuchile/bert-base-spanish-wwm-cased'
tokenizer = BertTokenizer.from_pretrained(model_name)
model_qa = BertForQuestionAnswering.from_pretrained(model_name)
nlp = pipeline("question-answering", model=model_qa, tokenizer=tokenizer)
embedder = SentenceTransformer('hiiamsid/sentence_similarity_spanish_es')

# Base de conocimiento
knowledge_base = {
    "textos": [],
    "embeddings": []
}

# Configuraci贸n de personalidad
personalidad = {
    "formal": True,
    "humor": 0.2,
    "temperatura": 0.7,
    "emojis": False
}

def cargar_conocimiento(archivo):
    """Carga conocimiento de diferentes formatos"""
    if archivo.name.endswith('.csv'):
        df = pd.read_csv(archivo.name)
        return df.to_dict('records')
    elif archivo.name.endswith('.xlsx'):
        df = pd.read_excel(archivo.name)
        return df.to_dict('records')
    elif archivo.name.endswith('.pdf'):
        reader = PdfReader(archivo.name)
        text = "\n".join([page.extract_text() for page in reader.pages])
        return [{"contenido": text}]
    return []

def actualizar_personalidad(formal, humor, temperatura, emojis):
    """Actualiza los par谩metros de personalidad"""
    personalidad["formal"] = formal
    personalidad["humor"] = humor
    personalidad["temperatura"] = temperatura
    personalidad["emojis"] = emojis
    return "Personalidad actualizada 鉁旓笍"

def procesar_pregunta(pregunta):
    """Procesa la pregunta usando el modelo y la base de conocimiento"""
    # Buscar en la base de conocimiento
    query_embedding = embedder.encode(pregunta)
    hits = util.semantic_search(query_embedding, knowledge_base["embeddings"], top_k=3)
    
    contexto = "\n".join([knowledge_base["textos"][hit['corpus_id']] 
                         for hit in hits[0]])
    
    # Generar respuesta con personalidad
    respuesta = nlp(question=pregunta, context=contexto)
    
    # Aplicar personalidad
    respuesta_texto = respuesta["answer"]
    if personalidad["formal"]:
        respuesta_texto = respuesta_texto.replace("Hola", "Buenos d铆as").replace("?", "驴?")
    if personalidad["emojis"]:
        respuesta_texto += " 馃槉" if "feliz" in pregunta.lower() else " 馃"
    
    return respuesta_texto

def cargar_archivo(archivo):
    """Carga el archivo a la base de conocimiento"""
    datos = cargar_conocimiento(archivo)
    textos = [str(registro) for registro in datos]
    embeddings = embedder.encode(textos)
    
    knowledge_base["textos"].extend(textos)
    knowledge_base["embeddings"].extend(embeddings)
    return f"隆Archivo cargado! Total de registros: {len(knowledge_base['textos'])}"

# Interfaz Gradio
with gr.Blocks(title="Bot Multifunci贸n") as demo:
    gr.Markdown("# 馃 Bot con Conocimiento y Personalidad Configurable")
    
    with gr.Tab("Cargar Conocimiento"):
        archivo = gr.File(label="Subir archivo (CSV/XLSX/PDF)")
        boton_cargar = gr.Button("Cargar Conocimiento")
        salida_carga = gr.Textbox(label="Estado", interactive=False)
        
    with gr.Tab("Configurar Personalidad"):
        formal = gr.Checkbox(label="Modo Formal", value=True)
        humor = gr.Slider(0, 1, 0.2, label="Nivel de Humor")
        temperatura = gr.Slider(0, 1, 0.7, label="Creatividad")
        emojis = gr.Checkbox(label="Usar Emojis", value=False)
        boton_personalidad = gr.Button("Actualizar Personalidad")
        salida_personalidad = gr.Textbox(label="Estado", interactive=False)
        
    with gr.Tab("Chat"):
        chatbot = gr.Chatbot()
        entrada = gr.Textbox(label="Escribe tu pregunta", placeholder="驴Qu茅 necesitas saber?")
        
    # Conexiones
    boton_cargar.click(cargar_archivo, inputs=archivo, outputs=salida_carga)
    boton_personalidad.click(actualizar_personalidad, 
                            inputs=[formal, humor, temperatura, emojis], 
                            outputs=salida_personalidad)
    entrada.submit(procesar_pregunta, entrada, chatbot)

# Ejecuci贸n
if __name__ == "__main__":
    demo.launch()