Spaces:
Running
Running
add fallback and method used
Browse files
services/new/__pycache__/cv_processor_v2.cpython-312.pyc
CHANGED
|
Binary files a/services/new/__pycache__/cv_processor_v2.cpython-312.pyc and b/services/new/__pycache__/cv_processor_v2.cpython-312.pyc differ
|
|
|
services/new/cv_processor_v2.py
CHANGED
|
@@ -7,6 +7,7 @@ import tempfile
|
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Any, Dict
|
| 9 |
|
|
|
|
| 10 |
from services.new.cv_converter_v2 import CvConverterV2
|
| 11 |
from services.new.google.gemini_extractor import GeminiCvExtractor
|
| 12 |
from services.processor_utils import (
|
|
@@ -20,7 +21,7 @@ logger = logging.getLogger(__name__)
|
|
| 20 |
|
| 21 |
|
| 22 |
class CvProcessorV2:
|
| 23 |
-
"""
|
| 24 |
|
| 25 |
def __init__(self) -> None:
|
| 26 |
self.converter = CvConverterV2()
|
|
@@ -28,8 +29,8 @@ class CvProcessorV2:
|
|
| 28 |
|
| 29 |
def process(self, file_bytes: bytes, filename: str) -> Dict[str, Any]:
|
| 30 |
"""
|
| 31 |
-
Convert file → markdown, then
|
| 32 |
-
|
| 33 |
"""
|
| 34 |
suffix = Path(filename).suffix.lower() if filename else ".pdf"
|
| 35 |
tmp_path = None
|
|
@@ -44,42 +45,72 @@ class CvProcessorV2:
|
|
| 44 |
if not conversion.success:
|
| 45 |
raise ValueError(conversion.error or "Conversion failed")
|
| 46 |
|
| 47 |
-
# Step 2 —
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
return {
|
| 61 |
-
|
| 62 |
-
"markdown":
|
| 63 |
-
"cv_title":
|
| 64 |
-
"seniority":
|
| 65 |
-
"years_experience":
|
| 66 |
-
"category":
|
| 67 |
-
"completeness_score":
|
| 68 |
-
"
|
| 69 |
-
"contact": extracted.get("contact", {}),
|
| 70 |
-
"links": extracted.get("links", []),
|
| 71 |
-
"skills": extracted.get("skills", {}),
|
| 72 |
-
"experience": extracted.get("experience", []),
|
| 73 |
-
"education": extracted.get("education", []),
|
| 74 |
-
"projects": extracted.get("projects", []),
|
| 75 |
-
"awards": extracted.get("awards", []),
|
| 76 |
-
"raw_sections": extracted.get("raw_sections", []),
|
| 77 |
-
"usage_metadata": extracted.get("usage_metadata", {}),
|
| 78 |
-
# ── Conversion metadata ──
|
| 79 |
"file_type": conversion.file_type,
|
| 80 |
"is_scanned": conversion.is_scanned,
|
| 81 |
"page_count": conversion.page_count,
|
| 82 |
-
"warnings":
|
| 83 |
}
|
| 84 |
|
| 85 |
finally:
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
from typing import Any, Dict
|
| 9 |
|
| 10 |
+
from services.cv_chunker import chunk_cv
|
| 11 |
from services.new.cv_converter_v2 import CvConverterV2
|
| 12 |
from services.new.google.gemini_extractor import GeminiCvExtractor
|
| 13 |
from services.processor_utils import (
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
class CvProcessorV2:
|
| 24 |
+
"""Processes CV using Gemini LLM with 3 retries, falling back to regex chunker if needed."""
|
| 25 |
|
| 26 |
def __init__(self) -> None:
|
| 27 |
self.converter = CvConverterV2()
|
|
|
|
| 29 |
|
| 30 |
def process(self, file_bytes: bytes, filename: str) -> Dict[str, Any]:
|
| 31 |
"""
|
| 32 |
+
Convert file → markdown, then extract fields via Gemini (or older chunk_cv on failure).
|
| 33 |
+
Returns payload including 'method_used': 'llm' | 'fallback'.
|
| 34 |
"""
|
| 35 |
suffix = Path(filename).suffix.lower() if filename else ".pdf"
|
| 36 |
tmp_path = None
|
|
|
|
| 45 |
if not conversion.success:
|
| 46 |
raise ValueError(conversion.error or "Conversion failed")
|
| 47 |
|
| 48 |
+
# Step 2 — Attempt Gemini extraction (handles up to 3 internal retries)
|
| 49 |
+
method_used = "llm"
|
| 50 |
+
extracted = None
|
| 51 |
+
try:
|
| 52 |
+
extracted = self.gemini_extractor.extract(conversion.markdown)
|
| 53 |
+
except Exception as gemini_err:
|
| 54 |
+
logger.warning(
|
| 55 |
+
"Gemini extraction failed after 3 retries (%s). Falling back to older regex chunk_cv...",
|
| 56 |
+
gemini_err,
|
| 57 |
+
)
|
| 58 |
+
method_used = "fallback"
|
| 59 |
|
| 60 |
+
warnings = list(conversion.warnings)
|
| 61 |
+
|
| 62 |
+
# --- LLM PATH ---
|
| 63 |
+
if method_used == "llm" and extracted:
|
| 64 |
+
skills_found = set(s.lower() for s in extracted.get("skills", {}).get("items", []))
|
| 65 |
+
if not skills_found:
|
| 66 |
+
skills_found = _extract_skills(conversion.markdown, DEFAULT_SKILL_ALIASES)
|
| 67 |
+
inferred_category = _infer_category(
|
| 68 |
+
text=conversion.markdown,
|
| 69 |
+
skills=skills_found,
|
| 70 |
+
category_skills=DEFAULT_CATEGORY_SKILLS,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
return {
|
| 74 |
+
"method_used": "llm",
|
| 75 |
+
"markdown": extracted.get("markdown", conversion.markdown),
|
| 76 |
+
"cv_title": extracted.get("cv_title", ""),
|
| 77 |
+
"seniority": extracted.get("seniority", "entry"),
|
| 78 |
+
"years_experience": extracted.get("years_experience", 0),
|
| 79 |
+
"category": inferred_category,
|
| 80 |
+
"completeness_score": extracted.get("completeness_score", 0),
|
| 81 |
+
"summary": extracted.get("summary", ""),
|
| 82 |
+
"contact": extracted.get("contact", {}),
|
| 83 |
+
"links": extracted.get("links", []),
|
| 84 |
+
"skills": extracted.get("skills", {}),
|
| 85 |
+
"experience": extracted.get("experience", []),
|
| 86 |
+
"education": extracted.get("education", []),
|
| 87 |
+
"projects": extracted.get("projects", []),
|
| 88 |
+
"awards": extracted.get("awards", []),
|
| 89 |
+
"raw_sections": extracted.get("raw_sections", []),
|
| 90 |
+
"usage_metadata": extracted.get("usage_metadata", {}),
|
| 91 |
+
"file_type": conversion.file_type,
|
| 92 |
+
"is_scanned": conversion.is_scanned,
|
| 93 |
+
"page_count": conversion.page_count,
|
| 94 |
+
"warnings": warnings,
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
# --- FALLBACK PATH (Returns older structure exactly as v1) ---
|
| 98 |
+
warnings.append("Gemini service unavailable. Parsed using regex fallback.")
|
| 99 |
+
chunks = chunk_cv(conversion.markdown)
|
| 100 |
|
| 101 |
return {
|
| 102 |
+
"method_used": "fallback",
|
| 103 |
+
"markdown": conversion.markdown,
|
| 104 |
+
"cv_title": chunks.get("cv_title", ""),
|
| 105 |
+
"seniority": chunks.get("seniority", "entry"),
|
| 106 |
+
"years_experience": chunks.get("years_experience", 0),
|
| 107 |
+
"category": chunks.get("category", "Other"),
|
| 108 |
+
"completeness_score": chunks.get("completeness_score", 0),
|
| 109 |
+
"chunks": chunks.get("chunks", {}),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
"file_type": conversion.file_type,
|
| 111 |
"is_scanned": conversion.is_scanned,
|
| 112 |
"page_count": conversion.page_count,
|
| 113 |
+
"warnings": warnings,
|
| 114 |
}
|
| 115 |
|
| 116 |
finally:
|
services/new/google/__pycache__/gemini_extractor.cpython-312.pyc
CHANGED
|
Binary files a/services/new/google/__pycache__/gemini_extractor.cpython-312.pyc and b/services/new/google/__pycache__/gemini_extractor.cpython-312.pyc differ
|
|
|
services/new/google/gemini_extractor.py
CHANGED
|
@@ -10,6 +10,7 @@ from __future__ import annotations
|
|
| 10 |
import json
|
| 11 |
import logging
|
| 12 |
import re
|
|
|
|
| 13 |
from typing import Any, Dict, List, Optional
|
| 14 |
import httpx
|
| 15 |
|
|
@@ -125,7 +126,7 @@ class GeminiCvExtractor:
|
|
| 125 |
self.model = model or GEMINI_MODEL
|
| 126 |
|
| 127 |
def _call_interactions(self, prompt: str, system_instruction: str = "") -> dict:
|
| 128 |
-
"""Call /v1beta/interactions
|
| 129 |
if not self.api_key or self.api_key == "YOUR_GEMINI_API_KEY_HERE":
|
| 130 |
raise ValueError("GEMINI_API_KEY is not set in processor/.env")
|
| 131 |
|
|
@@ -141,22 +142,46 @@ class GeminiCvExtractor:
|
|
| 141 |
if system_instruction:
|
| 142 |
body["system_instruction"] = system_instruction
|
| 143 |
|
|
|
|
|
|
|
|
|
|
| 144 |
with httpx.Client(timeout=60.0) as client:
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
def ping(self, prompt: str = "Say hello in one short sentence.") -> Dict[str, Any]:
|
| 162 |
"""Test API key and latency directly."""
|
|
|
|
| 10 |
import json
|
| 11 |
import logging
|
| 12 |
import re
|
| 13 |
+
import time
|
| 14 |
from typing import Any, Dict, List, Optional
|
| 15 |
import httpx
|
| 16 |
|
|
|
|
| 126 |
self.model = model or GEMINI_MODEL
|
| 127 |
|
| 128 |
def _call_interactions(self, prompt: str, system_instruction: str = "") -> dict:
|
| 129 |
+
"""Call /v1beta/interactions with 3 retries on 503 or transient errors."""
|
| 130 |
if not self.api_key or self.api_key == "YOUR_GEMINI_API_KEY_HERE":
|
| 131 |
raise ValueError("GEMINI_API_KEY is not set in processor/.env")
|
| 132 |
|
|
|
|
| 142 |
if system_instruction:
|
| 143 |
body["system_instruction"] = system_instruction
|
| 144 |
|
| 145 |
+
max_retries = 3
|
| 146 |
+
last_error = ""
|
| 147 |
+
|
| 148 |
with httpx.Client(timeout=60.0) as client:
|
| 149 |
+
for attempt in range(1, max_retries + 1):
|
| 150 |
+
try:
|
| 151 |
+
resp = client.post(url, headers=headers, json=body)
|
| 152 |
+
if resp.status_code == 200:
|
| 153 |
+
data = resp.json()
|
| 154 |
+
reply = ""
|
| 155 |
+
for step in data.get("steps", []):
|
| 156 |
+
for item in step.get("content", []):
|
| 157 |
+
if item.get("type") == "text":
|
| 158 |
+
reply += item.get("text", "")
|
| 159 |
+
|
| 160 |
+
return {
|
| 161 |
+
"text": reply.strip(),
|
| 162 |
+
"usage": data.get("usage", {}),
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
last_error = f"Gemini Interactions API error ({resp.status_code}): {resp.text}"
|
| 166 |
+
if resp.status_code in (429, 500, 502, 503, 504) and attempt < max_retries:
|
| 167 |
+
sleep_time = attempt * 1.5
|
| 168 |
+
logger.warning(
|
| 169 |
+
"Gemini attempt %d/%d failed (%d). Retrying in %.1fs...",
|
| 170 |
+
attempt, max_retries, resp.status_code, sleep_time
|
| 171 |
+
)
|
| 172 |
+
time.sleep(sleep_time)
|
| 173 |
+
continue
|
| 174 |
+
else:
|
| 175 |
+
raise RuntimeError(last_error)
|
| 176 |
+
|
| 177 |
+
except httpx.RequestError as exc:
|
| 178 |
+
last_error = f"Network error during Gemini call: {exc}"
|
| 179 |
+
if attempt < max_retries:
|
| 180 |
+
time.sleep(attempt * 1.5)
|
| 181 |
+
continue
|
| 182 |
+
raise RuntimeError(last_error)
|
| 183 |
+
|
| 184 |
+
raise RuntimeError(last_error or "Gemini API failed after 3 retries.")
|
| 185 |
|
| 186 |
def ping(self, prompt: str = "Say hello in one short sentence.") -> Dict[str, Any]:
|
| 187 |
"""Test API key and latency directly."""
|