Spaces:
Sleeping
Sleeping
Download app.py from auraailabs/buggy-copilot: direct link, hf CLI and curl.
- Browser
- Download file 7.44 kB
-
https://huggingface.co/spaces/auraailabs/buggy-copilot/resolve/main/app.py
- Command line
-
hf download hf://spaces/auraailabs/buggy-copilot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/auraailabs/buggy-copilot/resolve/main/app.py
7.44 kB
| """ | |
| AuraAI Labs — CV Summarizer Demo (Gradio) | |
| Sube CV (PDF/DOCX/TXT), indica Vacante y Empresa. Genera resumen orientado | |
| y guarda cada consulta en CSV/JSONL (./data/submissions.*). | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import csv | |
| import json | |
| import re | |
| import hashlib | |
| from datetime import datetime | |
| from typing import List, Tuple, Dict, Any | |
| import gradio as gr | |
| # ---------- Lectura de archivos ---------- | |
| def _read_pdf(path: str) -> str: | |
| try: | |
| from pypdf import PdfReader | |
| except Exception: | |
| from PyPDF2 import PdfReader # fallback | |
| text_parts: List[str] = [] | |
| reader = PdfReader(path) | |
| for page in getattr(reader, "pages", []): | |
| try: | |
| text_parts.append(page.extract_text() or "") | |
| except Exception: | |
| continue | |
| return "\n".join(text_parts) | |
| def _read_docx(path: str) -> str: | |
| from docx import Document | |
| doc = Document(path) | |
| return "\n".join(p.text for p in doc.paragraphs) | |
| def extract_text(file_path: str) -> str: | |
| ext = os.path.splitext(file_path.lower())[1] | |
| if ext == ".pdf": | |
| return _read_pdf(file_path) | |
| if ext == ".docx": | |
| return _read_docx(file_path) | |
| if ext == ".txt": | |
| with open(file_path, "r", encoding="utf-8", errors="ignore") as f: | |
| return f.read() | |
| raise ValueError(f"Formato no soportado: {ext}. Usa PDF/DOCX/TXT.") | |
| # ---------- NLP simple (sin LLM) ---------- | |
| def get_keywords(text: str, top_k: int = 12) -> List[str]: | |
| """Palabras/phrases clave usando RAKE + limpieza básica.""" | |
| import nltk | |
| from rake_nltk import Rake | |
| for pkg in ["punkt", "stopwords"]: | |
| try: | |
| nltk.data.find("tokenizers/punkt" if pkg == "punkt" else "corpora/stopwords") | |
| except LookupError: | |
| nltk.download(pkg, quiet=True) | |
| rake = Rake(language="spanish") | |
| rake.extract_keywords_from_text(text) | |
| ranked = rake.get_ranked_phrases() | |
| cleaned: List[str] = [] | |
| for kw in ranked: | |
| kw = kw.strip().lower() | |
| kw = re.sub(r"[^a-záéíóúñ0-9\-\+\.# ]", "", kw) | |
| if 2 <= len(kw) <= 40: | |
| cleaned.append(kw) | |
| seen, out = set(), [] | |
| for k in cleaned: | |
| if k not in seen: | |
| seen.add(k) | |
| out.append(k) | |
| if len(out) >= top_k: | |
| break | |
| return out | |
| def summarize(text: str, job_title: str, company: str, | |
| keywords: List[str], max_sentences: int = 6) -> str: | |
| """Resumen extractivo guiado por keywords + mini pitch.""" | |
| import nltk | |
| try: | |
| nltk.data.find("tokenizers/punkt") | |
| except LookupError: | |
| nltk.download("punkt", quiet=True) | |
| sents = nltk.sent_tokenize(text, language="spanish") | |
| kw_set = set(k.lower() for k in keywords) | |
| scored: List[Tuple[float, str]] = [] | |
| for s in sents: | |
| s_low = s.lower() | |
| score = sum(1 for k in kw_set if k in s_low) | |
| if len(s) > 20: | |
| scored.append((score, s.strip())) | |
| scored.sort(key=lambda x: (x[0], len(x[1])), reverse=True) | |
| selected = [s for _, s in scored[:max_sentences]] | |
| pitch = ( | |
| f"**Resumen para {job_title} en {company}**\n\n" | |
| f"- Enfoque: {job_title} · Empresa: {company}\n" | |
| f"- Competencias destacadas: {', '.join(keywords[:6]) if keywords else '—'}\n" | |
| f"- Propuesta: impacto en 90 días con KPIs acordados." | |
| ) | |
| body = "\n".join(f"- {s}" for s in selected) if selected else "- (No se hallaron frases representativas)." | |
| return pitch + "\n\n**Hechos relevantes del CV**\n" + body | |
| # ---------- Persistencia ---------- | |
| DATA_DIR = os.path.join(os.path.dirname(__file__), "data") | |
| os.makedirs(DATA_DIR, exist_ok=True) | |
| CSV_PATH = os.path.join(DATA_DIR, "submissions.csv") | |
| JSONL_PATH = os.path.join(DATA_DIR, "submissions.jsonl") | |
| def _init_csv() -> None: | |
| if not os.path.exists(CSV_PATH): | |
| with open(CSV_PATH, "w", newline="", encoding="utf-8") as f: | |
| w = csv.writer(f) | |
| w.writerow([ | |
| "timestamp", "session_id", "filename", "job_title", "company", | |
| "text_tokens", "text_hash", "top_keywords", "summary_chars" | |
| ]) | |
| _init_csv() | |
| def log_submission(session_id: str, filename: str, job_title: str, company: str, | |
| text: str, keywords: List[str], summary: str) -> None: | |
| ts = datetime.utcnow().isoformat() + "Z" | |
| text_hash = hashlib.sha256(text.encode("utf-8", errors="ignore")).hexdigest() | |
| with open(CSV_PATH, "a", newline="", encoding="utf-8") as f: | |
| csv.writer(f).writerow([ | |
| ts, session_id, filename, job_title, company, | |
| len(text.split()), text_hash, "|".join(keywords), len(summary) | |
| ]) | |
| with open(JSONL_PATH, "a", encoding="utf-8") as f: | |
| rec = { | |
| "timestamp": ts, "session_id": session_id, "filename": filename, | |
| "job_title": job_title, "company": company, | |
| "text_tokens": len(text.split()), "text_hash": text_hash, | |
| "keywords": keywords, "summary": summary | |
| } | |
| f.write(json.dumps(rec, ensure_ascii=False) + "\n") | |
| # ---------- Gradio UI ---------- | |
| def build_summary(file_obj, job_title: str, company: str, session_id: str): | |
| if not file_obj: | |
| raise gr.Error("Sube un archivo PDF/DOCX/TXT.") | |
| if not job_title.strip() or not company.strip(): | |
| raise gr.Error("Completa 'Vacante' y 'Empresa'.") | |
| text = extract_text(file_obj.name) | |
| if len(text.strip()) < 40: | |
| raise gr.Error("No pude extraer texto útil. ¿El PDF es escaneado? (haz OCR).") | |
| keywords = get_keywords(text, top_k=12) | |
| summary_md = summarize(text, job_title.strip(), company.strip(), keywords, max_sentences=6) | |
| filename = os.path.basename(file_obj.name) | |
| log_submission(session_id, filename, job_title.strip(), company.strip(), text, keywords, summary_md) | |
| debug = { | |
| "filename": filename, | |
| "tokens": len(text.split()), | |
| "keywords": keywords, | |
| "csv_path": CSV_PATH, | |
| "jsonl_path": JSONL_PATH, | |
| } | |
| return summary_md, debug | |
| def download_logs(kind: str) -> str: | |
| return CSV_PATH if kind == "csv" else JSONL_PATH | |
| with gr.Blocks(title="AuraAI — CV Summarizer", css=".gradio-container{max-width:880px}") as demo: | |
| gr.Markdown("# CV ➜ Resumen orientado a vacante\nSube tu CV, indica Vacante y Empresa. Guardamos cada consulta.") | |
| with gr.Row(): | |
| file_in = gr.File(label="CV (PDF/DOCX/TXT)", file_count="single", type="filepath") | |
| with gr.Row(): | |
| job = gr.Textbox(label="Vacante", placeholder="Ej. Data Scientist", max_lines=1) | |
| company = gr.Textbox(label="Empresa", placeholder="Nombre de la empresa", max_lines=1) | |
| session = gr.State(value=os.environ.get("SESSION_ID", "anon")) | |
| run = gr.Button("Generar resumen", variant="primary") | |
| out_md = gr.Markdown(label="Resumen") | |
| out_dbg = gr.JSON(label="Detalles (debug/keywords)") | |
| with gr.Accordion("Descargar logs (admin)", open=False): | |
| dl_csv = gr.DownloadButton("Descargar CSV") | |
| dl_jsonl = gr.DownloadButton("Descargar JSONL") | |
| run.click(build_summary, inputs=[file_in, job, company, session], outputs=[out_md, out_dbg]) | |
| dl_csv.click(lambda: download_logs("csv"), outputs=dl_csv) | |
| dl_jsonl.click(lambda: download_logs("jsonl"), outputs=dl_jsonl) | |
| gr.Markdown("*Privacidad:* Guardamos metadatos, keywords y el resumen. No almacenamos el archivo original.") | |
| if __name__ == "__main__": | |
| demo.launch() | |