Download app.py from Carlox2/tutor: direct link, hf CLI and curl.
- Browser
- Download file 6.14 kB
-
https://huggingface.co/spaces/Carlox2/tutor/resolve/main/app.py
- Command line
-
hf download hf://spaces/Carlox2/tutor/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Carlox2/tutor/resolve/main/app.py
6.14 kB
| 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.") |