Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,9 +2,9 @@ import os
|
|
| 2 |
import io
|
| 3 |
import json
|
| 4 |
import hashlib
|
| 5 |
-
import gradio
|
| 6 |
import gradio as gr
|
| 7 |
-
from typing import
|
| 8 |
|
| 9 |
from pipelines.openai_ingest import (
|
| 10 |
extract_text_with_openai,
|
|
@@ -14,60 +14,82 @@ from pipelines.openai_ingest import (
|
|
| 14 |
from pipelines.parsing import normalize_resume
|
| 15 |
from pipelines.merge import merge_normalized_records
|
| 16 |
from pipelines.skills import extract_skills
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
from pipelines.scoring import compute_quality_score
|
| 19 |
from pipelines.storage import persist_to_hf
|
| 20 |
from pipelines.utils import detect_filetype, load_doc_text
|
| 21 |
|
| 22 |
APP_TITLE = "候補者インテーク & レジュメ標準化(OpenAI版)"
|
| 23 |
|
| 24 |
-
# ---- helpers ---------------------------------------------------------------
|
| 25 |
-
|
| 26 |
-
def _read_file_input(item: Union[str, "gradio.files.TempFile"]) -> Tuple[bytes, str]:
|
| 27 |
-
"""
|
| 28 |
-
Gradio v4.44 の Files(type='filepath') は str パスを返す。
|
| 29 |
-
互換のため、パス/ファイルライク双方を許容して (bytes, filename) を返す。
|
| 30 |
-
"""
|
| 31 |
-
if isinstance(item, str):
|
| 32 |
-
with open(item, "rb") as rf:
|
| 33 |
-
data = rf.read()
|
| 34 |
-
name = os.path.basename(item)
|
| 35 |
-
return data, name
|
| 36 |
-
# UploadedFile 等(念のため)
|
| 37 |
-
if hasattr(item, "read"):
|
| 38 |
-
data = item.read()
|
| 39 |
-
name = getattr(item, "name", "uploaded")
|
| 40 |
-
return data, os.path.basename(name)
|
| 41 |
-
raise ValueError("Unsupported file input type")
|
| 42 |
-
|
| 43 |
|
| 44 |
-
def
|
| 45 |
-
|
|
|
|
| 46 |
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
| 51 |
if not files:
|
| 52 |
raise gr.Error("少なくとも1ファイルをアップロードしてください。")
|
| 53 |
|
| 54 |
partial_records = []
|
| 55 |
raw_texts = []
|
| 56 |
|
| 57 |
-
for
|
| 58 |
-
|
| 59 |
-
|
|
|
|
| 60 |
|
| 61 |
# 1) テキスト抽出:画像/PDFはOpenAI Vision OCR、docx/txtは生文面+OpenAI整形
|
| 62 |
if filetype in {"pdf", "image"}:
|
| 63 |
-
text = extract_text_with_openai(raw_bytes, filename=
|
| 64 |
else:
|
| 65 |
base_text = load_doc_text(filetype, raw_bytes)
|
| 66 |
-
text = extract_text_with_openai(base_text.encode("utf-8"), filename=
|
| 67 |
|
| 68 |
-
raw_texts.append({"filename":
|
| 69 |
|
| 70 |
-
# 2) OpenAIでセクション構造化 →
|
| 71 |
structured = structure_with_openai(text)
|
| 72 |
normalized = normalize_resume({
|
| 73 |
"work_experience": structured.get("work_experience_raw", ""),
|
|
@@ -76,16 +98,16 @@ def process_resumes(files: List[Union[str, "gradio.files.TempFile"]], candidate_
|
|
| 76 |
"skills": ", ".join(structured.get("skills_list", [])),
|
| 77 |
})
|
| 78 |
partial_records.append({
|
| 79 |
-
"source":
|
| 80 |
"text": text,
|
| 81 |
"structured": structured,
|
| 82 |
"normalized": normalized,
|
| 83 |
})
|
| 84 |
|
| 85 |
-
# 3)
|
| 86 |
merged = merge_normalized_records([r["normalized"] for r in partial_records])
|
| 87 |
|
| 88 |
-
# 4)
|
| 89 |
merged_text = "\n\n".join([r["text"] for r in partial_records])
|
| 90 |
skills = extract_skills(merged_text, {
|
| 91 |
"work_experience": merged.get("raw_sections", {}).get("work_experience", ""),
|
|
@@ -101,13 +123,14 @@ def process_resumes(files: List[Union[str, "gradio.files.TempFile"]], candidate_
|
|
| 101 |
# 6) 品質スコア
|
| 102 |
score = compute_quality_score(merged_text, merged)
|
| 103 |
|
| 104 |
-
# 7)
|
| 105 |
summaries = summarize_with_openai(merged_text)
|
| 106 |
|
| 107 |
# 8) 構造化出力
|
|
|
|
| 108 |
result_json = {
|
| 109 |
-
"candidate_id":
|
| 110 |
-
"files": [os.path.basename(
|
| 111 |
"merged": merged,
|
| 112 |
"skills": skills,
|
| 113 |
"quality_score": score,
|
|
@@ -116,38 +139,39 @@ def process_resumes(files: List[Union[str, "gradio.files.TempFile"]], candidate_
|
|
| 116 |
"notes": additional_notes,
|
| 117 |
}
|
| 118 |
|
| 119 |
-
# 9) HF Datasets
|
| 120 |
dataset_repo = os.environ.get("DATASET_REPO")
|
| 121 |
commit_info = None
|
| 122 |
if dataset_repo:
|
| 123 |
-
file_hash = result_json["candidate_id"]
|
| 124 |
commit_info = persist_to_hf(
|
| 125 |
dataset_repo=dataset_repo,
|
| 126 |
record=result_json,
|
| 127 |
anon_pdf_bytes=anon_pdf_bytes,
|
| 128 |
-
parquet_path=f"candidates/{
|
| 129 |
-
json_path=f"candidates/{
|
| 130 |
-
pdf_path=f"candidates/{
|
| 131 |
)
|
| 132 |
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
# 返却はすべて文字列 or ファイル
|
| 136 |
return (
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
summaries.get("300chars", ""),
|
| 141 |
summaries.get("100chars", ""),
|
| 142 |
summaries.get("onesent", ""),
|
| 143 |
anon_pdf,
|
| 144 |
-
|
| 145 |
)
|
| 146 |
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
with gr.Blocks(title=APP_TITLE, analytics_enabled=False) as demo:
|
| 151 |
gr.Markdown(f"# {APP_TITLE}\n複数ファイルを統合→OpenAIで読み込み/構造化/要約→匿名化→Datasets保存")
|
| 152 |
|
| 153 |
with gr.Row():
|
|
@@ -155,7 +179,7 @@ with gr.Blocks(title=APP_TITLE, analytics_enabled=False) as demo:
|
|
| 155 |
label="レジュメ類 (PDF/画像/Word/テキスト) 複数可",
|
| 156 |
file_count="multiple",
|
| 157 |
file_types=[".pdf", ".png", ".jpg", ".jpeg", ".tiff", ".bmp", ".docx", ".txt"],
|
| 158 |
-
type="filepath", #
|
| 159 |
)
|
| 160 |
candidate_id = gr.Textbox(label="候補者ID(任意。未入力なら自動生成)")
|
| 161 |
notes = gr.Textbox(label="補足メモ(任意)", lines=3)
|
|
@@ -166,8 +190,7 @@ with gr.Blocks(title=APP_TITLE, analytics_enabled=False) as demo:
|
|
| 166 |
out_json = gr.Code(label="統合出力 (JSON)")
|
| 167 |
|
| 168 |
with gr.Tab("抽出スキル"):
|
| 169 |
-
|
| 170 |
-
out_skills = gr.Code(label="スキル一覧 (JSON)")
|
| 171 |
|
| 172 |
with gr.Tab("品質スコア"):
|
| 173 |
out_score = gr.Code(label="品質評価 (JSON)")
|
|
@@ -184,14 +207,12 @@ with gr.Blocks(title=APP_TITLE, analytics_enabled=False) as demo:
|
|
| 184 |
out_commit = gr.Code(label="コミット情報 (JSON)")
|
| 185 |
|
| 186 |
run_btn.click(
|
| 187 |
-
process_resumes,
|
| 188 |
inputs=[in_files, candidate_id, notes],
|
| 189 |
outputs=[out_json, out_skills, out_score, out_sum_300, out_sum_100, out_sum_1, out_pdf, out_commit],
|
|
|
|
| 190 |
)
|
| 191 |
|
| 192 |
-
|
| 193 |
if __name__ == "__main__":
|
| 194 |
-
#
|
| 195 |
-
|
| 196 |
-
share_flag = share_env in ("1", "true", "yes", "on")
|
| 197 |
-
demo.launch(server_name="0.0.0.0", server_port=7860, share=share_flag)
|
|
|
|
| 2 |
import io
|
| 3 |
import json
|
| 4 |
import hashlib
|
| 5 |
+
import gradio # 前方参照の解決用(必要なら)
|
| 6 |
import gradio as gr
|
| 7 |
+
from typing import Any, List
|
| 8 |
|
| 9 |
from pipelines.openai_ingest import (
|
| 10 |
extract_text_with_openai,
|
|
|
|
| 14 |
from pipelines.parsing import normalize_resume
|
| 15 |
from pipelines.merge import merge_normalized_records
|
| 16 |
from pipelines.skills import extract_skills
|
| 17 |
+
|
| 18 |
+
# ---- anonymize フォールバック(pipelines/anonymize.py が未実装でも動く) ----
|
| 19 |
+
try:
|
| 20 |
+
from pipelines.anonymize import anonymize_text, render_anonymized_pdf # type: ignore
|
| 21 |
+
except Exception:
|
| 22 |
+
import re
|
| 23 |
+
try:
|
| 24 |
+
from reportlab.pdfgen import canvas
|
| 25 |
+
from reportlab.lib.pagesizes import A4
|
| 26 |
+
except Exception:
|
| 27 |
+
canvas = None
|
| 28 |
+
A4 = None
|
| 29 |
+
|
| 30 |
+
def anonymize_text(text: str):
|
| 31 |
+
# 超簡易:メール/電話っぽい所をマスク。氏名は見出し候補を雑にマスク。
|
| 32 |
+
masked = re.sub(r"([A-Za-z0-9._%+-]+)@([A-Za-z0-9.-]+\.[A-Za-z]{2,})", r"***@\2", text)
|
| 33 |
+
masked = re.sub(r"(?:\+?\d{1,3}[ -]?)?(?:\(\d{2,4}\)[ -]?)?\d{2,4}[ -]?\d{2,4}[ -]?\d{3,4}", "***-****-****", masked)
|
| 34 |
+
masked = re.sub(r"(氏名[::]?\s*)(\S+)", r"\1***", masked)
|
| 35 |
+
return masked, {"fallback": True}
|
| 36 |
+
|
| 37 |
+
def render_anonymized_pdf(text: str) -> bytes:
|
| 38 |
+
if canvas is None:
|
| 39 |
+
# reportlab が無ければテキストファイルで代替(UIは .pdf 名で返す)
|
| 40 |
+
return text.encode("utf-8")
|
| 41 |
+
buf = io.BytesIO()
|
| 42 |
+
c = canvas.Canvas(buf, pagesize=A4)
|
| 43 |
+
width, height = A4
|
| 44 |
+
margin = 40
|
| 45 |
+
y = height - margin
|
| 46 |
+
for line in text.splitlines() or ["(no content)"]:
|
| 47 |
+
if y < margin:
|
| 48 |
+
c.showPage()
|
| 49 |
+
y = height - margin
|
| 50 |
+
c.drawString(margin, y, line[:95])
|
| 51 |
+
y -= 14
|
| 52 |
+
c.save()
|
| 53 |
+
return buf.getvalue()
|
| 54 |
+
# ---------------------------------------------------------------------------
|
| 55 |
+
|
| 56 |
from pipelines.scoring import compute_quality_score
|
| 57 |
from pipelines.storage import persist_to_hf
|
| 58 |
from pipelines.utils import detect_filetype, load_doc_text
|
| 59 |
|
| 60 |
APP_TITLE = "候補者インテーク & レジュメ標準化(OpenAI版)"
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
def _read_bytes_from_path(path: str) -> bytes:
|
| 64 |
+
with open(path, "rb") as f:
|
| 65 |
+
return f.read()
|
| 66 |
|
| 67 |
|
| 68 |
+
def process_resumes(files: List[str], candidate_id: str = "", additional_notes: str = ""):
|
| 69 |
+
"""
|
| 70 |
+
files: gr.Files(type='filepath') から渡るファイルパスのリスト
|
| 71 |
+
"""
|
| 72 |
if not files:
|
| 73 |
raise gr.Error("少なくとも1ファイルをアップロードしてください。")
|
| 74 |
|
| 75 |
partial_records = []
|
| 76 |
raw_texts = []
|
| 77 |
|
| 78 |
+
for path in files:
|
| 79 |
+
filename = os.path.basename(path)
|
| 80 |
+
raw_bytes = _read_bytes_from_path(path)
|
| 81 |
+
filetype = detect_filetype(filename, raw_bytes)
|
| 82 |
|
| 83 |
# 1) テキスト抽出:画像/PDFはOpenAI Vision OCR、docx/txtは生文面+OpenAI整形
|
| 84 |
if filetype in {"pdf", "image"}:
|
| 85 |
+
text = extract_text_with_openai(raw_bytes, filename=filename, filetype=filetype)
|
| 86 |
else:
|
| 87 |
base_text = load_doc_text(filetype, raw_bytes)
|
| 88 |
+
text = extract_text_with_openai(base_text.encode("utf-8"), filename=filename, filetype="txt")
|
| 89 |
|
| 90 |
+
raw_texts.append({"filename": filename, "text": text})
|
| 91 |
|
| 92 |
+
# 2) OpenAIでセクション構造化 → ルール正規化
|
| 93 |
structured = structure_with_openai(text)
|
| 94 |
normalized = normalize_resume({
|
| 95 |
"work_experience": structured.get("work_experience_raw", ""),
|
|
|
|
| 98 |
"skills": ", ".join(structured.get("skills_list", [])),
|
| 99 |
})
|
| 100 |
partial_records.append({
|
| 101 |
+
"source": filename,
|
| 102 |
"text": text,
|
| 103 |
"structured": structured,
|
| 104 |
"normalized": normalized,
|
| 105 |
})
|
| 106 |
|
| 107 |
+
# 3) 統合(複数ファイル→1候補者)
|
| 108 |
merged = merge_normalized_records([r["normalized"] for r in partial_records])
|
| 109 |
|
| 110 |
+
# 4) スキル抽出(辞書/正規表現)
|
| 111 |
merged_text = "\n\n".join([r["text"] for r in partial_records])
|
| 112 |
skills = extract_skills(merged_text, {
|
| 113 |
"work_experience": merged.get("raw_sections", {}).get("work_experience", ""),
|
|
|
|
| 123 |
# 6) 品質スコア
|
| 124 |
score = compute_quality_score(merged_text, merged)
|
| 125 |
|
| 126 |
+
# 7) 要約(300/100/1文)
|
| 127 |
summaries = summarize_with_openai(merged_text)
|
| 128 |
|
| 129 |
# 8) 構造化出力
|
| 130 |
+
cid = candidate_id or hashlib.sha256(merged_text.encode("utf-8")).hexdigest()[:16]
|
| 131 |
result_json = {
|
| 132 |
+
"candidate_id": cid,
|
| 133 |
+
"files": [os.path.basename(p) for p in files],
|
| 134 |
"merged": merged,
|
| 135 |
"skills": skills,
|
| 136 |
"quality_score": score,
|
|
|
|
| 139 |
"notes": additional_notes,
|
| 140 |
}
|
| 141 |
|
| 142 |
+
# 9) HF Datasets 保存(任意)
|
| 143 |
dataset_repo = os.environ.get("DATASET_REPO")
|
| 144 |
commit_info = None
|
| 145 |
if dataset_repo:
|
|
|
|
| 146 |
commit_info = persist_to_hf(
|
| 147 |
dataset_repo=dataset_repo,
|
| 148 |
record=result_json,
|
| 149 |
anon_pdf_bytes=anon_pdf_bytes,
|
| 150 |
+
parquet_path=f"candidates/{cid}.parquet",
|
| 151 |
+
json_path=f"candidates/{cid}.json",
|
| 152 |
+
pdf_path=f"candidates/{cid}.anon.pdf",
|
| 153 |
)
|
| 154 |
|
| 155 |
+
# UI 向け出力を整形
|
| 156 |
+
anon_pdf = (f"{cid}.anon.pdf", anon_pdf_bytes)
|
| 157 |
+
out_json_str = json.dumps(result_json, ensure_ascii=False, indent=2)
|
| 158 |
+
out_skills_str = json.dumps(skills, ensure_ascii=False, indent=2) # gr.Code で表示
|
| 159 |
+
out_score_str = json.dumps(score, ensure_ascii=False, indent=2)
|
| 160 |
+
out_commit_str = json.dumps(commit_info or {"status": "skipped (DATASET_REPO not set)"}, ensure_ascii=False, indent=2)
|
| 161 |
|
|
|
|
| 162 |
return (
|
| 163 |
+
out_json_str,
|
| 164 |
+
out_skills_str,
|
| 165 |
+
out_score_str,
|
| 166 |
summaries.get("300chars", ""),
|
| 167 |
summaries.get("100chars", ""),
|
| 168 |
summaries.get("onesent", ""),
|
| 169 |
anon_pdf,
|
| 170 |
+
out_commit_str,
|
| 171 |
)
|
| 172 |
|
| 173 |
|
| 174 |
+
with gr.Blocks(title=APP_TITLE) as demo:
|
|
|
|
|
|
|
| 175 |
gr.Markdown(f"# {APP_TITLE}\n複数ファイルを統合→OpenAIで読み込み/構造化/要約→匿名化→Datasets保存")
|
| 176 |
|
| 177 |
with gr.Row():
|
|
|
|
| 179 |
label="レジュメ類 (PDF/画像/Word/テキスト) 複数可",
|
| 180 |
file_count="multiple",
|
| 181 |
file_types=[".pdf", ".png", ".jpg", ".jpeg", ".tiff", ".bmp", ".docx", ".txt"],
|
| 182 |
+
type="filepath", # ★ 重要:'file' ではなく 'filepath'
|
| 183 |
)
|
| 184 |
candidate_id = gr.Textbox(label="候補者ID(任意。未入力なら自動生成)")
|
| 185 |
notes = gr.Textbox(label="補足メモ(任意)", lines=3)
|
|
|
|
| 190 |
out_json = gr.Code(label="統合出力 (JSON)")
|
| 191 |
|
| 192 |
with gr.Tab("抽出スキル"):
|
| 193 |
+
out_skills = gr.Code(label="スキル一覧 (JSON)") # ★ JSON -> Code に���更
|
|
|
|
| 194 |
|
| 195 |
with gr.Tab("品質スコア"):
|
| 196 |
out_score = gr.Code(label="品質評価 (JSON)")
|
|
|
|
| 207 |
out_commit = gr.Code(label="コミット情報 (JSON)")
|
| 208 |
|
| 209 |
run_btn.click(
|
| 210 |
+
fn=process_resumes,
|
| 211 |
inputs=[in_files, candidate_id, notes],
|
| 212 |
outputs=[out_json, out_skills, out_score, out_sum_300, out_sum_100, out_sum_1, out_pdf, out_commit],
|
| 213 |
+
api_name="run",
|
| 214 |
)
|
| 215 |
|
|
|
|
| 216 |
if __name__ == "__main__":
|
| 217 |
+
# 環境により localhost へ到達できない場合があるため share=True を既定に
|
| 218 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|
|
|
|
|
|