Spaces:
Paused
Paused
Download backend/cv.py from hatethisworld/AI-Interview: direct link, hf CLI and curl.
- Browser
- Download file 2.12 kB
-
https://huggingface.co/spaces/hatethisworld/AI-Interview/resolve/main/backend/cv.py
- Command line
-
hf download hf://spaces/hatethisworld/AI-Interview/backend/cv.py
-
curl -L -o cv.py https://huggingface.co/spaces/hatethisworld/AI-Interview/resolve/main/backend/cv.py
2.12 kB
| """Read an uploaded PDF CV in memory; never save the file or its text.""" | |
| from io import BytesIO | |
| from fastapi import HTTPException | |
| from pypdf import PdfReader | |
| MAX_CV_BYTES = 5 * 1024 * 1024 | |
| MAX_CV_PAGES = 10 | |
| MAX_CV_TEXT = 20_000 | |
| def read_cv(content: bytes, filename: str) -> dict: | |
| filename = filename.replace("\\", "/").rsplit("/", 1)[-1] | |
| if not filename.lower().endswith(".pdf") or len(filename) > 255: | |
| raise HTTPException(415, "只能上传 PDF 格式的 CV。") | |
| if len(content) > MAX_CV_BYTES: | |
| raise HTTPException(413, "CV 文件不能超过 5 MB。") | |
| if not content: | |
| raise HTTPException(422, "文件为空,请重新选择 PDF。") | |
| if not content.startswith(b"%PDF-"): | |
| raise HTTPException(415, "文件内容不是有效的 PDF,请勿只修改文件扩展名。") | |
| try: | |
| reader = PdfReader(BytesIO(content)) | |
| if reader.is_encrypted: | |
| raise HTTPException(422, "暂不支持加密 PDF,请上传不带密码的版本。") | |
| page_count = len(reader.pages) | |
| if not 1 <= page_count <= MAX_CV_PAGES: | |
| raise HTTPException(422, "请上传 1–10 页的 CV。") | |
| parts = [] | |
| for page in reader.pages: | |
| contents = page.get_contents() | |
| if contents is not None and len(contents.get_data()) > 5 * 1024 * 1024: | |
| raise HTTPException(422, "PDF 页面过于复杂,请导出为简化的文本 PDF 后重试。") | |
| parts.append((page.extract_text() or "").strip()) | |
| if sum(map(len, parts)) + len(parts) - 1 > MAX_CV_TEXT: | |
| raise HTTPException(422, "CV 文字过长,请精简至 20,000 个字符以内。") | |
| text = "\n".join(parts).strip() | |
| except HTTPException: | |
| raise | |
| except Exception as exc: | |
| raise HTTPException(422, "无法读取此 PDF,文件可能已损坏。请重新导出后上传。") from exc | |
| if not text: | |
| raise HTTPException(422, "未读取到文字。请上传可复制文字的 PDF,扫描件暂不支持。") | |
| return {"filename": filename, "text": text, "pages": page_count} | |