File size: 2,212 Bytes
3a006a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()