Spaces:
Runtime error

File size: 6,144 Bytes
16cf051
 
 
f506c6d
7e99375
16cf051
 
 
35ed2ae
f506c6d
 
16cf051
1e041a6
4295215
16cf051
a5ef14b
16cf051
 
 
1e041a6
16cf051
 
 
 
 
 
 
 
 
 
 
 
7e99375
16cf051
f506c6d
 
 
 
16cf051
 
f506c6d
16cf051
f506c6d
16cf051
f506c6d
 
 
 
 
 
 
16cf051
 
f506c6d
 
16cf051
f506c6d
 
16cf051
 
 
 
 
f506c6d
16cf051
 
 
 
 
f506c6d
7e99375
 
 
 
f506c6d
 
16cf051
7e99375
f506c6d
16cf051
f506c6d
16cf051
 
 
 
 
 
f506c6d
 
16cf051
 
 
 
 
f506c6d
 
16cf051
 
 
 
 
 
 
 
f506c6d
16cf051
 
4295215
16cf051
 
 
 
f506c6d
7e99375
16cf051
 
 
f506c6d
7e99375
 
 
 
f506c6d
16cf051
f506c6d
 
 
 
 
 
 
16cf051
 
f506c6d
16cf051
7e99375
f506c6d
7e99375
f506c6d
7e99375
 
f506c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e99375
f506c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import os
import tempfile
import base64
import asyncio
import gradio as gr
import chromadb
from chromadb.utils import embedding_functions
from PyPDF2 import PdfReader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from groq import Groq
import edge_tts

# ========== CONFIGURACIÓN ==========
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
if not GROQ_API_KEY:
    raise ValueError("Falta la variable de entorno GROQ_API_KEY")

groq_client = Groq(api_key=GROQ_API_KEY)

# ========== CHROMADB ==========
CHROMA_PATH = "./chroma_db"
os.makedirs(CHROMA_PATH, exist_ok=True)

embedder = embedding_functions.SentenceTransformerEmbeddingFunction(
    model_name="all-MiniLM-L6-v2"
)
chroma_client = chromadb.PersistentClient(path=CHROMA_PATH)
collection = chroma_client.get_or_create_collection(
    name="pdfs",
    embedding_function=embedder
)

# ========== FUNCIONES ==========
def index_pdfs(files):
    if not files:
        return "❌ No se seleccionaron archivos"
    
    # Limpiar colección anterior
    if collection.count() > 0:
        collection.delete(ids=[str(i) for i in range(collection.count())])
    
    all_text = ""
    for file_obj in files:
        try:
            # file_obj.name es la ruta del archivo temporal
            with open(file_obj.name, 'rb') as f:
                reader = PdfReader(f)
                for page in reader.pages:
                    text = page.extract_text()
                    if text:
                        all_text += text + "\n"
        except Exception as e:
            print(f"Error leyendo PDF: {e}")
            return f"❌ Error al leer PDF: {str(e)}"
    
    if not all_text.strip():
        return "❌ No se pudo extraer texto de los PDFs. Asegúrate de que sean PDFs con texto."
    
    splitter = RecursiveCharacterTextSplitter(
        chunk_size=500,
        chunk_overlap=50
    )
    chunks = splitter.split_text(all_text)
    
    for i, chunk in enumerate(chunks):
        collection.add(
            documents=[chunk],
            ids=[str(i)]
        )
    
    return f"✅ {len(chunks)} fragmentos indexados correctamente."

def process_audio(audio_file):
    if audio_file is None:
        return "❌ No se recibió audio", None
    
    try:
        # 1. Transcripción con Whisper (Groq)
        with open(audio_file, "rb") as f:
            transcription = groq_client.audio.transcriptions.create(
                file=(audio_file, f.read()),
                model="whisper-large-v3",
                language="es",
                response_format="text"
            )
        user_text = transcription
        print(f"👤 Usuario: {user_text}")
        
        # 2. Búsqueda en PDFs (RAG)
        results = collection.query(query_texts=[user_text], n_results=3)
        context = ""
        if results and results['documents']:
            context = "\n".join(results['documents'][0])
        print(f"📚 Contexto: {context[:200]}...")
        
        # 3. Generar respuesta con Qwen 2.5
        prompt = f"""Eres un tutor experto. Responde la pregunta usando SOLO el siguiente contexto extraído de los documentos. Si el contexto no tiene la respuesta, di "No encuentro esa información en los documentos".

Contexto:
{context}

Pregunta del usuario: {user_text}

Respuesta:"""
        
        chat_completion = groq_client.chat.completions.create(
            messages=[{"role": "user", "content": prompt}],
            model="qwen-2.5-72b",
            temperature=0.7,
        )
        answer_text = chat_completion.choices[0].message.content
        print(f"🤖 Respuesta: {answer_text}")
        
        # 4. Texto a voz con Edge TTS
        voice = "es-MX-DaliaNeural"
        communicate = edge_tts.Communicate(answer_text, voice)
        audio_bytes = b""
        async def get_audio():
            nonlocal audio_bytes
            async for chunk in communicate.stream():
                if chunk["type"] == "audio":
                    audio_bytes += chunk["data"]
        asyncio.run(get_audio())
        
        # Guardar audio temporal
        audio_temp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
        audio_temp.write(audio_bytes)
        audio_temp.close()
        
        return answer_text, audio_temp.name
    
    except Exception as e:
        print(f"❌ Error: {e}")
        return f"❌ Error: {str(e)}", None

# ========== INTERFAZ GRADIO ==========
with gr.Blocks(title="Tutor GEM", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# 🎤 Tutor GEM")
    gr.Markdown("Asistente educativo con Qwen 2.5, RAG y voz.")
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### 📄 Base de conocimiento")
            pdf_files = gr.File(
                label="Sube tus PDFs",
                file_types=[".pdf"],
                file_count="multiple"
            )
            upload_btn = gr.Button("📤 Indexar PDFs", variant="primary")
            upload_status = gr.Textbox(
                label="Estado",
                interactive=False,
                lines=2
            )
            upload_btn.click(
                index_pdfs,
                inputs=pdf_files,
                outputs=upload_status
            )
        
        with gr.Column(scale=1):
            gr.Markdown("### 🎙️ Pregunta")
            audio_input = gr.Audio(
                sources=["microphone"],
                type="filepath",
                label="Presiona el micrófono y habla"
            )
            text_output = gr.Textbox(
                label="📝 Respuesta en texto",
                interactive=False,
                lines=6
            )
            audio_output = gr.Audio(
                label="🔊 Respuesta en voz",
                type="filepath"
            )
            audio_input.change(
                process_audio,
                inputs=audio_input,
                outputs=[text_output, audio_output]
            )
    
    gr.Markdown("---")
    gr.Markdown("💡 **Instrucciones**: 1) Sube tus PDFs y haz clic en 'Indexar PDFs'. 2) Presiona el micrófono, habla tu pregunta y suelta. 3) Escucharás la respuesta.")