import os import tempfile from markitdown import MarkItDown from app.services.ai_service import extract_cv_metadata from loguru import logger class CVParser: @staticmethod async def parse_to_markdown(file_bytes: bytes, filename: str) -> str: """Converts raw file bytes to Markdown text using MarkItDown.""" ext = ".pdf" low_name = filename.lower() if low_name.endswith(".docx"): ext = ".docx" elif low_name.endswith(".doc"): ext = ".doc" elif low_name.endswith(".html") or low_name.endswith(".htm"): ext = ".html" elif low_name.endswith(".txt"): ext = ".txt" temp_path = None try: with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp_file: temp_file.write(file_bytes) temp_path = temp_file.name markitdown = MarkItDown() result = markitdown.convert(temp_path) return result.text_content except Exception as e: logger.error(f"CV conversion failed: {e}") raise e finally: if temp_path and os.path.exists(temp_path): try: os.remove(temp_path) except: pass @staticmethod async def analyze_cv(file_bytes: bytes, filename: str): """Full pipeline: Convert to MD -> Extract Metadata via Gemini.""" try: markdown_text = await CVParser.parse_to_markdown(file_bytes, filename) if not markdown_text or len(markdown_text.strip()) < 50: return {"error": "Teks CV terlalu pendek atau tidak terbaca."} # Use the existing ai_service metadata extractor metadata = await extract_cv_metadata(markdown_text) return { "success": True, "markdown": markdown_text, "metadata": metadata } except Exception as e: logger.error(f"CV analysis pipeline failed: {e}") return {"error": str(e)} cv_parser = CVParser()