update
Browse filesFiles changed (13)
- backend/app/__pycache__/main.cpython-310.pyc
- backend/app/schemas.py+3
- backend/app/unittest/test_paper_ocr.py+56
- backend/common/hf_storage.pyAdded+182
- backend/common/paper_columns.py+18
- backend/common/paper_ocr/router.py+78-3
- backend/meloonexam/schemas.py+4
- backend/requirements.txt+1
- frontend/MeloonExam/src/App.tsx+22-2
- frontend/MeloonExam/src/components/OriginalFileViewer.tsx+50-32
- frontend/MeloonExam/src/components/PaperUploadModal.tsx+65-10
- frontend/MeloonExam/src/services/apiClient.ts+81-2
- frontend/MeloonExam/src/types/index.ts+6
146 unmodified lines147148149150151152146 unmodified lineshasAnswer: bool = TruehasAnalysis: bool = TruefileSizeMb: Optional[float] = 3.0class ExamPaperResponse(ExamPaperCreate):146 unmodified lines147148149150151152153154155146 unmodified lineshasAnswer: bool = TruehasAnalysis: bool = TruefileSizeMb: Optional[float] = 3.0# HuggingFace Storage bucket 字段fileUrl: Optional[str] = NonehfDestPath: Optional[str] = Noneclass ExamPaperResponse(ExamPaperCreate):
356 unmodified lines357358359360361356 unmodified linesself.assertTrue(callable(worker.main))if __name__ == "__main__":unittest.main()356 unmodified lines357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417356 unmodified linesself.assertTrue(callable(worker.main))class TestHfStorageIntegration(unittest.TestCase):def setUp(self):from common.paper_ocr.router import router as paper_ocr_routerapp = FastAPI()app.include_router(paper_ocr_router, prefix="/api/papers")self.client = TestClient(app)def test_url_builders(self):from common import hf_storageurl = hf_storage.build_public_url("papers/paper-123.pdf")self.assertEqual(url,"https://huggingface.co/buckets/isold23/MeloonHub-storage/resolve/papers/paper-123.pdf",)dl_url = hf_storage.build_download_url("papers/paper-123.pdf")self.assertEqual(dl_url,"https://huggingface.co/buckets/isold23/MeloonHub-storage/resolve/papers/paper-123.pdf?download=true",)def test_upload_file_endpoint(self):from common import hf_storagewith unittest.mock.patch.object(hf_storage, "is_available", lambda: True), \unittest.mock.patch.object(hf_storage,"upload_file",lambda content, dest, content_type=None: (dest, f"https://huggingface.co/buckets/isold23/MeloonHub-storage/resolve/{dest}"),):res = self.client.post("/api/papers/upload-file",files={"file": ("test.pdf", b"%PDF-1.4 mock content", "application/pdf")},data={"paper_id": "test-paper-001"},)self.assertEqual(res.status_code, 200, res.text)data = res.json()self.assertTrue(data["success"])self.assertIn("https://huggingface.co/buckets/isold23/MeloonHub-storage/resolve/papers/test-paper-001.pdf", data["file_url"])self.assertIn("download=true", data["download_url"])def test_storage_file_redirect(self):res = self.client.get("/api/papers/storage-file/papers/mock.pdf", follow_redirects=False)self.assertEqual(res.status_code, 307)self.assertEqual(res.headers["location"],"https://huggingface.co/buckets/isold23/MeloonHub-storage/resolve/papers/mock.pdf",)res_dl = self.client.get("/api/papers/storage-file/papers/mock.pdf?download=true", follow_redirects=False)self.assertEqual(res_dl.status_code, 307)self.assertEqual(res_dl.headers["location"],"https://huggingface.co/buckets/isold23/MeloonHub-storage/resolve/papers/mock.pdf?download=true",)if __name__ == "__main__":unittest.main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182"""HuggingFace Storage Buckets 集成模块。
负责将 MeloonExam 上传的试卷文件(PDF / 图片 / Word)持久化到HuggingFace 私有/公开对象存储 ``isold23/MeloonHub-storage`` bucket,并返回可公开访问的直链 URL 供前端预览与下载。
Hugging Face Storage Buckets 架构: • 存储桶页面: https://huggingface.co/buckets/isold23/MeloonHub-storage • 页面加载/预览直链: https://huggingface.co/buckets/isold23/MeloonHub-storage/resolve/{path} • 强制下载直链: https://huggingface.co/buckets/isold23/MeloonHub-storage/resolve/{path}?download=true • API 交互: huggingface_hub.batch_bucket_files / list_bucket_tree / download_bucket_files"""
from __future__ import annotations
import loggingimport osfrom pathlib import Pathfrom typing import List, Optional, Tuple
logger = logging.getLogger(__name__)
# ──────────────────────────────────────────────────────────────────────────────# 配置常量# ──────────────────────────────────────────────────────────────────────────────HF_NAMESPACE = os.getenv("HF_NAMESPACE", "isold23")HF_BUCKET_NAME = os.getenv("HF_BUCKET_NAME", "MeloonHub-storage")HF_BUCKET_ID = f"{HF_NAMESPACE}/{HF_BUCKET_NAME}"
def _load_hf_token() -> Optional[str]: """获取 HuggingFace Token,按环境变量 -> 本地缓存的优先级读取。""" token = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_TOKEN") or os.getenv("HF_API_TOKEN") if token: return token.strip() cache_token_path = Path.home() / ".cache" / "huggingface" / "token" if cache_token_path.exists(): try: return cache_token_path.read_text(encoding="utf-8").strip() except Exception: pass return None
HF_TOKEN = _load_hf_token()
# HuggingFace Storage Buckets 统一访问 URL 模板_HF_RESOLVE_URL_TMPL = "https://huggingface.co/buckets/{namespace}/{bucket}/resolve/{path}"
def build_public_url(dest_path: str) -> str: """根据 bucket 路径构造供前端页面加载/预览使用的公开直链。
例如: https://huggingface.co/buckets/isold23/MeloonHub-storage/resolve/papers/2026/paper-123.pdf 该直链在浏览器中默认返回 inline Content-Disposition,支持直接嵌入 PDF 预览或 <img> 渲染。 """ clean_path = dest_path.strip().lstrip("/") return _HF_RESOLVE_URL_TMPL.format( namespace=HF_NAMESPACE, bucket=HF_BUCKET_NAME, path=clean_path, )
def build_download_url(dest_path: str) -> str: """根据 bucket 路径构造强制下载直链(携带 ?download=true 触发浏览器附件下载)。""" return f"{build_public_url(dest_path)}?download=true"
def is_available() -> bool: """检查 HF Storage 是否已可用(已安装依赖且有 token)。""" try: from huggingface_hub import batch_bucket_files # noqa: F401 return bool(_load_hf_token()) except ImportError: return False
# ──────────────────────────────────────────────────────────────────────────────# 核心操作函数# ──────────────────────────────────────────────────────────────────────────────
def upload_file( content: bytes, dest_path: str, *, content_type: Optional[str] = None,) -> Tuple[str, str]: """将文件字节直接写入 Hugging Face Storage bucket,返回 (dest_path, public_url)。
Args: content: 文件字节内容(PDF / 图片 / docx 等)。 dest_path: bucket 内的目标相对路径,例如 ``papers/paper-123/math-gaokao.pdf``。 content_type: MIME 类型提示(可选)。
Returns: ``(dest_path, public_url)`` — 目标路径与可公开加载的直链。
Raises: RuntimeError: 上传失败或依赖未安装。 """ token = _load_hf_token() if not token: raise RuntimeError( "HF_TOKEN 未配置,无法上传文件到 HuggingFace Storage Bucket。" "请在后端 .env 中设置 HF_TOKEN 或通过 `hf login` 登录。" )
clean_dest = dest_path.strip().lstrip("/") try: from huggingface_hub import batch_bucket_files except ImportError as exc: raise RuntimeError( "huggingface_hub 未安装或版本过低,请确认已安装 >= 1.5.0 支持 buckets" ) from exc
try: batch_bucket_files( bucket_id=HF_BUCKET_ID, add=[(content, clean_dest)], token=token, ) except Exception as exc: logger.error("HuggingFace bucket 文件上传失败 [%s]: %s", clean_dest, exc) raise RuntimeError(f"文件上传至 HuggingFace bucket 失败: {exc}") from exc
public_url = build_public_url(clean_dest) logger.info("文件已成功持久化至 HF bucket: %s -> %s", clean_dest, public_url) return clean_dest, public_url
def delete_file(dest_path: str) -> bool: """从 HuggingFace Storage bucket 中删除指定文件。返回是否成功。""" token = _load_hf_token() if not token: logger.warning("HF_TOKEN 未配置,跳过 HF bucket 文件删除: %s", dest_path) return False
clean_dest = dest_path.strip().lstrip("/") try: from huggingface_hub import batch_bucket_files batch_bucket_files( bucket_id=HF_BUCKET_ID, delete=[clean_dest], token=token, ) logger.info("HF bucket 文件已删除: %s", clean_dest) return True except Exception as exc: logger.warning("HF bucket 文件删除失败 [%s]: %s", clean_dest, exc) return False
def download_file(dest_path: str) -> bytes: """从 HuggingFace Storage bucket 读取文件字节。""" import requests
public_url = build_public_url(dest_path) resp = requests.get(public_url, allow_redirects=True, timeout=60) if resp.status_code == 200: return resp.content
# 若公网 URL 无法直接匿名读取(如设为 private bucket),使用 token 认证下载 token = _load_hf_token() headers = {"Authorization": f"Bearer {token}"} if token else {} resp = requests.get(public_url, headers=headers, allow_redirects=True, timeout=60) if resp.status_code == 200: return resp.content
raise FileNotFoundError(f"从 HF bucket 获取文件失败 [{resp.status_code}]: {dest_path}")
def list_files(prefix: Optional[str] = None) -> List[str]: """列出 HuggingFace Storage bucket 中的文件路径列表。""" try: from huggingface_hub import list_bucket_tree token = _load_hf_token() tree = list_bucket_tree(bucket_id=HF_BUCKET_ID, prefix=prefix, recursive=True, token=token) return [item.path for item in tree if getattr(item, "type", None) == "file" or hasattr(item, "size")] except Exception as exc: logger.error("列举 HF bucket 文件失败: %s", exc) return []25 unmodified lines26272829303128 unmodified lines6061626364656667686925 unmodified lines"viewCount": "view_count","likeCount": "like_count","createdAt": "created_at",}PAPER_COLUMNS = {28 unmodified linescamelCase keys are rewritten to snake_case and any key that is not a realcolumn is dropped, so an unexpected field can never break the write."""row: Dict[str, Any] = {}for key, value in raw.items():column = PAPER_COLUMN_MAP.get(key, key)if column in PAPER_COLUMNS:row[column] = valuereturn row25 unmodified lines262728293031323328 unmodified lines626364656667686970717273747576777879808182838485868725 unmodified lines"viewCount": "view_count","likeCount": "like_count","createdAt": "created_at","fileUrl": "file_url","hfDestPath": "hf_dest_path",}PAPER_COLUMNS = {28 unmodified linescamelCase keys are rewritten to snake_case and any key that is not a realcolumn is dropped, so an unexpected field can never break the write.``file_url`` and ``hf_dest_path`` are embedded inside the ``contributor``jsonb column to ensure persistence without schema alteration."""row: Dict[str, Any] = {}for key, value in raw.items():column = PAPER_COLUMN_MAP.get(key, key)if column in PAPER_COLUMNS:row[column] = value# Preserve file_url and hf_dest_path in contributor jsonb if providedfile_url = raw.get("file_url") or raw.get("fileUrl")hf_dest_path = raw.get("hf_dest_path") or raw.get("hfDestPath")if file_url or hf_dest_path:contributor = row.get("contributor") or {}if isinstance(contributor, dict):contributor = dict(contributor)if file_url:contributor["file_url"] = file_urlif hf_dest_path:contributor["hf_dest_path"] = hf_dest_pathrow["contributor"] = contributorreturn row
1 unmodified line23456789103 unmodified lines141516171819202122232425103 unmodified lines1291301311 unmodified line统一挂载在 ``/api/papers`` 前缀下,与试卷 CRUD 路由同源:* ``GET /api/papers/ocr-status`` —— PaddleOCR 引擎自检(是否安装、版本、是否已加载模型)* ``POST /api/papers/parse-ocr`` —— 上传试卷文件 -> OCR 识别 -> 结构化试题* ``POST /api/papers/parse-text`` —— 解析纯文本(教师手动补录 / 联调自测).. warning::``/ocr-status`` 必须比 ``papers.router`` 的 ``GET /{paper_id}`` **先注册**,3 unmodified linesfrom __future__ import annotationsimport loggingfrom typing import Any, Dict, Optionalfrom fastapi import APIRouter, File, Form, HTTPException, UploadFilefrom fastapi.concurrency import run_in_threadpoolfrom pydantic import BaseModel, ConfigDict, Fieldfrom .engine import is_availablefrom .runtime import ocr_runtime_status, resolve_ocr_pythonfrom .service import MAX_PAGES_LIMIT, parse_paper_bytes, parse_paper_text103 unmodified linesfull_score=payload.full_score,)return result.to_dict()1 unmodified line2345678910113 unmodified lines151617181920212223242526272829103 unmodified lines1331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052061 unmodified line统一挂载在 ``/api/papers`` 前缀下,与试卷 CRUD 路由同源:* ``GET /api/papers/ocr-status`` —— PaddleOCR 引擎自检(是否安装、版本、是否已加载模型)* ``POST /api/papers/parse-ocr`` —— 上传试卷文件 -> OCR 识别 -> 结构化试题* ``POST /api/papers/parse-text`` —— 解析纯文本(教师手动补录 / 联调自测)* ``POST /api/papers/upload-file`` —— 上传试卷原文件到 HuggingFace Storage bucket,返回 file_url.. warning::``/ocr-status`` 必须比 ``papers.router`` 的 ``GET /{paper_id}`` **先注册**,3 unmodified linesfrom __future__ import annotationsimport loggingimport uuidfrom pathlib import Pathfrom typing import Any, Dict, Optionalfrom fastapi import APIRouter, File, Form, HTTPException, UploadFilefrom fastapi.concurrency import run_in_threadpoolfrom pydantic import BaseModel, ConfigDict, Fieldfrom common import hf_storagefrom .engine import is_availablefrom .runtime import ocr_runtime_status, resolve_ocr_pythonfrom .service import MAX_PAGES_LIMIT, parse_paper_bytes, parse_paper_text103 unmodified linesfull_score=payload.full_score,)return result.to_dict()@router.post("/upload-file", summary="上传试卷原文件到 HuggingFace Storage bucket")async def upload_paper_file(file: UploadFile = File(..., description="试卷原文件(PDF / PNG / JPG / WEBP)"),paper_id: Optional[str] = Form(None, description="试卷 ID(用于 bucket 路径前缀,可选)"),) -> Dict[str, Any]:"""将试卷二进制文件上传到 HuggingFace Storage bucket,返回可公开访问的 file_url。前端在「发布试卷」之前调用此接口,把原始 PDF / 图片存储到云端,并将返回的 ``file_url`` 一并写入 exam_paper 表,供后续预览与下载使用。依赖环境变量 ``HF_TOKEN`` 方可访问 HuggingFace Storage API。若未配置 token,返回 503。"""if not hf_storage.is_available():raise HTTPException(status_code=503,detail=("HuggingFace Storage 未配置:请在后端 .env 中设置 HF_TOKEN=hf_... ""(从 https://huggingface.co/settings/tokens 生成 Write 权限 token)"),)raw = await file.read()if not raw:raise HTTPException(status_code=400, detail="上传文件内容为空")if len(raw) > MAX_UPLOAD_BYTES:raise HTTPException(status_code=413,detail=f"文件过大({len(raw) / 1024 / 1024:.1f}MB),上限为 {MAX_UPLOAD_BYTES // 1024 // 1024}MB",)filename = file.filename or "paper.bin"suffix = Path(filename).suffix.lower() or ".bin"unique_name = f"{paper_id or uuid.uuid4().hex[:12]}{suffix}"dest_path = f"papers/{unique_name}"try:_, public_url = await run_in_threadpool(hf_storage.upload_file,raw,dest_path,content_type=file.content_type,)except RuntimeError as exc:logger.error("HF Storage 上传失败: %s", exc)raise HTTPException(status_code=502, detail=str(exc)) from excreturn {"success": True,"file_url": public_url,"download_url": hf_storage.build_download_url(dest_path),"dest_path": dest_path,"filename": filename,"size_bytes": len(raw),}@router.get("/storage-file/{file_path:path}", summary="重定向或获取 HuggingFace Storage bucket 文件")async def get_storage_file(file_path: str, download: bool = False):"""从 HuggingFace Storage bucket 加载文件。若 download=True,返回强制下载直链;否则返回可用于嵌入预览(PDF/图片)的直链。"""from fastapi.responses import RedirectResponsetarget_url = (hf_storage.build_download_url(file_path)if downloadelse hf_storage.build_public_url(file_path))return RedirectResponse(url=target_url, status_code=307)
184 unmodified lines185186187188189190184 unmodified lineshas_analysis: bool = Truefile_size_mb: float = 3.2is_featured: bool = Falseclass ExamPaperResponse(ExamPaperCreate):184 unmodified lines185186187188189190191192193194184 unmodified lineshas_analysis: bool = Truefile_size_mb: float = 3.2is_featured: bool = False# HuggingFace Storage bucket 的试卷原文件公开 URL(PDF / 图片)file_url: Optional[str] = None# HuggingFace bucket 内部路径,用于后续删除(如 "papers/paper-abc123.pdf")hf_dest_path: Optional[str] = Noneclass ExamPaperResponse(ExamPaperCreate):
23 unmodified lines24252623 unmodified linestabulateneo4jnetworkx23 unmodified lines2425262723 unmodified linestabulateneo4jnetworkxhuggingface_hub
281 unmodified lines28228328428528628728814 unmodified lines303304305306307308309281 unmodified linesif (refreshedUser) setCurrentUser(refreshedUser);}// If paper has an uploaded PDF or file attachment, download the file directlyif (paper.fileAttachment) {let downloadUrl = paper.fileAttachment.previewUrl;if (!downloadUrl && (paper.fileAttachment as any).file) {14 unmodified linesdocument.body.appendChild(link);link.click();document.body.removeChild(link);showToast(`✅ PDF试卷原件下载成功: ${paper.title}`);return;} catch (e) {console.error('Direct download error:', e);281 unmodified lines28228328428528628728828929029129229329429529629729829930030130230330430530630730814 unmodified lines323324325326327328329281 unmodified linesif (refreshedUser) setCurrentUser(refreshedUser);}// 1. 如果试卷在 HuggingFace Storage bucket 中存储了原文件,直接从 bucket 触发下载const bucketUrl = paper.downloadUrl || paper.fileUrl;if (bucketUrl) {try {const downloadLink = bucketUrl.includes('?') ? `${bucketUrl}&download=true` : `${bucketUrl}?download=true`;const link = document.createElement('a');link.href = downloadLink;const ext = paper.sourceFormat === 'word' ? 'docx' : paper.sourceFormat === 'image' ? 'png' : 'pdf';link.download = `${paper.title || '试卷原件'}.${ext}`;link.target = '_blank';document.body.appendChild(link);link.click();document.body.removeChild(link);showToast(`✅ 已从 HuggingFace 存储桶下载试卷: ${paper.title}`);return;} catch (e) {console.error('HuggingFace bucket download error:', e);}}// 2. 如果关联了本地/临时 fileAttachment,直接下载附件if (paper.fileAttachment) {let downloadUrl = paper.fileAttachment.previewUrl;if (!downloadUrl && (paper.fileAttachment as any).file) {14 unmodified linesdocument.body.appendChild(link);link.click();document.body.removeChild(link);showToast(`✅ 试卷原件下载成功: ${paper.title}`);return;} catch (e) {console.error('Direct download error:', e);
33 unmodified lines343536373839408 unmodified lines49505152535479 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117233 unmodified linesconst fileType = fileAtt?.type || (paper.sourceFormat || 'pdf');const fileName = fileAtt?.name || `${paper.title}.${fileType === 'word' ? 'docx' : fileType === 'image' ? 'png' : 'pdf'}`;const fileSize = fileAtt?.sizeMb || 2.4;const previewUrl = fileAtt?.previewUrl;return (<div className={`flex flex-col bg-slate-100 rounded-2xl border border-slate-200 overflow-hidden shadow-inner ${8 unmodified lines}`}>{fileType}</div><div className="flex flex-col min-w-0"><span className="text-xs sm:text-sm font-bold truncate">{fileName}</span><span className="text-[10px] text-slate-400">79 unmodified lines</div></div>) : fileType === 'pdf' && previewUrl ? (<div className="w-full min-h-[750px] flex flex-col items-center justify-center p-8 bg-slate-50 space-y-6"><div className="w-20 h-20 bg-red-100 text-red-600 rounded-3xl flex items-center justify-center shadow-md"><FileText className="w-10 h-10" /></div><div className="text-center space-y-2 max-w-md"><h3 className="text-lg font-bold text-slate-900">{fileName}</h3><p className="text-xs text-slate-500">PDF 试卷原件已安全挂载 (大小: {fileSize} MB)。由于浏览器安全策略限制直接嵌入预览,您可以点击下方按钮在新标签页中高清查阅或下载。</p></div><div className="flex items-center space-x-3 pt-2"><ahref={previewUrl}target="_blank"rel="noopener noreferrer"className="px-5 py-2.5 bg-red-600 hover:bg-red-700 text-white rounded-xl font-bold text-xs shadow-md transition-colors flex items-center space-x-2 cursor-pointer"><ExternalLink className="w-4 h-4" /><span>在新标签页中完整查看 PDF</span></a><buttontype="button"onClick={() => onDownload(paper)}className="px-5 py-2.5 bg-slate-900 hover:bg-slate-800 text-white rounded-xl font-bold text-xs shadow-md transition-colors flex items-center space-x-2 cursor-pointer"><Download className="w-4 h-4" /><span>下载 PDF 原件</span></button></div><div className="w-full border-t border-slate-200 pt-6 mt-4"><p className="text-xs text-slate-400 text-center">或切换至「试卷研读与详解」模式查阅结构化题目与公式解析。</p></div></div>) : (33 unmodified lines34353637383940418 unmodified lines505152535455565758596061626364656679 unmodified lines14614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919033 unmodified linesconst fileType = fileAtt?.type || (paper.sourceFormat || 'pdf');const fileName = fileAtt?.name || `${paper.title}.${fileType === 'word' ? 'docx' : fileType === 'image' ? 'png' : 'pdf'}`;const fileSize = fileAtt?.sizeMb || 2.4;const previewUrl = paper.fileUrl || fileAtt?.previewUrl;const isFromBucket = Boolean(paper.fileUrl || (previewUrl && previewUrl.includes('huggingface.co/buckets')));return (<div className={`flex flex-col bg-slate-100 rounded-2xl border border-slate-200 overflow-hidden shadow-inner ${8 unmodified lines}`}>{fileType}</div>{isFromBucket && (<ahref="https://huggingface.co/buckets/isold23/MeloonHub-storage"target="_blank"rel="noopener noreferrer"className="hidden sm:inline-flex items-center space-x-1 px-2 py-0.5 rounded text-[10px] font-bold bg-amber-500/20 text-amber-300 border border-amber-500/40 hover:bg-amber-500/30 transition-colors"title="来自 Hugging Face Storage Bucket: isold23/MeloonHub-storage"><span>🤗 HF Bucket 加载</span></a>)}<div className="flex flex-col min-w-0"><span className="text-xs sm:text-sm font-bold truncate">{fileName}</span><span className="text-[10px] text-slate-400">79 unmodified lines</div></div>) : fileType === 'pdf' && previewUrl ? (<div className="w-full h-full min-h-[780px] flex flex-col p-4 bg-slate-50 space-y-3"><div className="flex flex-wrap items-center justify-between gap-2 px-3 py-2 bg-white border border-slate-200 rounded-xl text-xs shadow-xs"><div className="flex items-center space-x-2 min-w-0"><FileText className="w-4 h-4 text-red-500 shrink-0" /><span className="font-bold text-slate-800 truncate">{fileName}</span>{isFromBucket && (<span className="text-[10px] px-2 py-0.5 bg-emerald-100 text-emerald-800 rounded-full font-medium shrink-0">已从 HF 存储桶加载</span>)}</div><div className="flex items-center space-x-2 shrink-0"><ahref={previewUrl}target="_blank"rel="noopener noreferrer"className="px-3 py-1.5 text-slate-600 hover:text-slate-900 hover:bg-slate-100 rounded-lg text-xs font-semibold flex items-center space-x-1 transition-colors"><ExternalLink className="w-3.5 h-3.5" /><span>新窗口查阅</span></a><buttontype="button"onClick={() => onDownload(paper)}className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold flex items-center space-x-1 shadow-xs transition-colors cursor-pointer"><Download className="w-3.5 h-3.5" /><span>下载原件</span></button></div></div>{/* PDF In-page Embedded Frame */}<div className="flex-1 w-full min-h-[720px] bg-white rounded-xl overflow-hidden border border-slate-300 shadow-inner"><iframesrc={previewUrl}title={fileName}className="w-full h-full min-h-[720px] border-0"/></div></div>) : (
389 unmodified lines39039139239339439539639739839940040140240340414 unmodified lines41942042142242342412 unmodified lines437438439440441442443444445446447448449450451769 unmodified lines12211222122312241225122612271228122912301231123212331 unmodified line1235123612371238123912401241124212431244124512461247124812491250389 unmodified linessetQuestions(questions.filter((q) => q.id !== id));};const handlePublishPaper = (e: React.FormEvent) => {e.preventDefault();if (!title.trim()) {alert('请填写试卷名称');return;}const newPaper: ExamPaper = {id: `paper-user-${Date.now()}`,title: title.trim(),stage,subject,14 unmodified linesavatar: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=100&auto=format&fit=crop&q=80',schoolOrRole: contributorSchool.trim() || 'Meloon 共享贡献者',badge: '热心贡献名师',},createdAt: new Date().toISOString(),questions,12 unmodified linesname: uploadedFile.name,sizeMb: uploadedFile.sizeMb,type: uploadedFile.type,previewUrl: uploadedFile.previewUrl,}: undefined,};onSavePaper(newPaper);onClose();};if (!isOpen) return null;return (769 unmodified lines{/* Action Submit */}<div className="pt-4 border-t border-slate-200 flex flex-col sm:flex-row items-center justify-between gap-3"><div className="text-xs text-slate-500 flex items-center space-x-1">{uploadedFile ? (<span className="text-emerald-700 font-semibold flex items-center space-x-1"><Paperclip className="w-3.5 h-3.5" /><span>已关联源文件: {uploadedFile.name} ({uploadedFile.type.toUpperCase()})</span></span>) : (<span>💡 提示:支持直接拖拽 PDF、Word 或试卷图片一键上传</span>)}</div>1 unmodified line<buttontype="button"onClick={onClose}className="px-4 py-2 text-xs font-semibold text-slate-600 hover:bg-slate-100 rounded-xl transition-colors cursor-pointer">取消</button><buttontype="submit"className="px-5 py-2 text-xs font-bold text-white bg-emerald-600 hover:bg-emerald-700 rounded-xl shadow-xs transition-colors flex items-center space-x-1.5 active:scale-95 cursor-pointer"><UploadCloud className="w-4 h-4" /><span>立即发布并共享试卷</span></button></div></div>389 unmodified lines39039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243314 unmodified lines44844945045145245345445545612 unmodified lines469470471472473474475476477478479480481482483484485486487488489490769 unmodified lines1260126112621263126412651266126712681269127012711272127312741275127612771 unmodified line127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305389 unmodified linessetQuestions(questions.filter((q) => q.id !== id));};const [isPublishing, setIsPublishing] = useState(false);const [publishStep, setPublishStep] = useState('');const handlePublishPaper = async (e: React.FormEvent) => {e.preventDefault();if (!title.trim()) {alert('请填写试卷名称');return;}setIsPublishing(true);const paperId = `paper-user-${Date.now()}`;// 1. 先把原文件上传到 HuggingFace Storage bucket (isold23/MeloonHub-storage),获取 file_urllet fileUrl: string | undefined;let downloadUrl: string | undefined;let hfDestPath: string | undefined;if (uploadedFile?.file) {setPublishStep('正在上传原文件到 HuggingFace Storage (isold23/MeloonHub-storage)...');try {const stored = await apiClient.uploadFileToStorage(uploadedFile.file, paperId);if (stored) {fileUrl = stored.fileUrl;downloadUrl = stored.downloadUrl;hfDestPath = stored.destPath;console.info('[PaperUpload] 文件已成功写入 HuggingFace bucket:', fileUrl);} else {console.warn('[PaperUpload] HF Storage 上传不可用或网络异常,跳过文件上传');}} catch (err) {console.warn('[PaperUpload] 文件上传异常,继续发布元数据:', err);}}setPublishStep('正在发布试卷到题库...');const newPaper: ExamPaper = {id: paperId,title: title.trim(),stage,subject,14 unmodified linesavatar: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=100&auto=format&fit=crop&q=80',schoolOrRole: contributorSchool.trim() || 'Meloon 共享贡献者',badge: '热心贡献名师',file_url: fileUrl,download_url: downloadUrl,hf_dest_path: hfDestPath,},createdAt: new Date().toISOString(),questions,12 unmodified linesname: uploadedFile.name,sizeMb: uploadedFile.sizeMb,type: uploadedFile.type,previewUrl: fileUrl || uploadedFile.previewUrl,}: undefined,// HuggingFace Storage bucket 原文件公开直链与下载直链fileUrl,downloadUrl,hfDestPath,};setIsPublishing(false);setPublishStep('');onSavePaper(newPaper);onClose();};if (!isOpen) return null;return (769 unmodified lines{/* Action Submit */}<div className="pt-4 border-t border-slate-200 flex flex-col sm:flex-row items-center justify-between gap-3"><div className="text-xs text-slate-500 flex items-center space-x-1">{isPublishing ? (<span className="text-emerald-700 font-bold flex items-center space-x-1.5 animate-pulse"><Loader2 className="w-3.5 h-3.5 animate-spin" /><span>{publishStep || '正在处理并同步至云端...'}</span></span>) : uploadedFile ? (<span className="text-emerald-700 font-semibold flex items-center space-x-1"><Paperclip className="w-3.5 h-3.5" /><span>已关联源文件: {uploadedFile.name} ({uploadedFile.type.toUpperCase()}) • 自动存入 HF Bucket</span></span>) : (<span>💡 提示:支持直接拖拽 PDF、Word 或试卷图片一键上传(自动存入 HuggingFace 存储桶)</span>)}</div>1 unmodified line<buttontype="button"onClick={onClose}disabled={isPublishing}className="px-4 py-2 text-xs font-semibold text-slate-600 hover:bg-slate-100 rounded-xl transition-colors cursor-pointer disabled:opacity-50">取消</button><buttontype="submit"disabled={isPublishing}className="px-5 py-2 text-xs font-bold text-white bg-emerald-600 hover:bg-emerald-700 rounded-xl shadow-xs transition-colors flex items-center space-x-1.5 active:scale-95 cursor-pointer disabled:opacity-60 disabled:cursor-not-allowed">{isPublishing ? (<><Loader2 className="w-4 h-4 animate-spin" /><span>{publishStep || '发布中...'}</span></>) : (<><UploadCloud className="w-4 h-4" /><span>立即发布并共享试卷</span></>)}</button></div></div>
70 unmodified lines7172737475761239 unmodified lines131613171318131913201321132235 unmodified lines13581359136013611362136313646 unmodified lines1371137213731374137513768 unmodified lines138513861387138813891390139170 unmodified linesknowledgePoints: Array.isArray(q.knowledgePoints) ? q.knowledgePoints : Array.isArray(q.knowledge_points) ? q.knowledge_points : [],options: Array.isArray(q.options) ? q.options : [],})) : [],};}1239 unmodified linesreturn res.paper;}public async uploadPaper(paper: ExamPaper): Promise<ExamPaper> {const res = await this.saveUploadedPaper(paper);return res.paper;}35 unmodified lines}}// 兼具兼容驼峰与下划线的 payloadconst payloadForBackend = {...normalizedPaper,full_score: normalizedPaper.fullScore,6 unmodified lineslike_count: normalizedPaper.likeCount,is_featured: normalizedPaper.isFeatured,created_at: normalizedPaper.createdAt,};// 1. 依次尝试 FastAPI 接口8 unmodified linesif (res.ok) {const data = await res.json();if (data && (data.id || data.title || data.status === 'success')) {savedPaper = normalizePaper(data.data || data);isPersisted = true;persistedTarget = 'fastapi';endpointUsed = ep;70 unmodified lines717273747576777879808182838485861239 unmodified lines13261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138235 unmodified lines14181419142014211422142314246 unmodified lines14311432143314341435143614371438143914401441144214431444144514461447144814498 unmodified lines145814591460146114621463146414651466146714681469147070 unmodified linesknowledgePoints: Array.isArray(q.knowledgePoints) ? q.knowledgePoints : Array.isArray(q.knowledge_points) ? q.knowledge_points : [],options: Array.isArray(q.options) ? q.options : [],})) : [],// HuggingFace Storage bucket 原文件 URL(页面加载与直链下载)fileUrl: raw.fileUrl ?? raw.file_url ?? raw.contributor?.file_url ?? raw.contributor?.fileUrl ?? undefined,downloadUrl: raw.downloadUrl ?? raw.download_url ?? ((raw.fileUrl ?? raw.file_url ?? raw.contributor?.file_url ?? raw.contributor?.fileUrl)? `${raw.fileUrl ?? raw.file_url ?? raw.contributor?.file_url ?? raw.contributor?.fileUrl}${String(raw.fileUrl ?? raw.file_url ?? raw.contributor?.file_url ?? '').includes('?') ? '&' : '?'}download=true`: undefined),hfDestPath: raw.hfDestPath ?? raw.hf_dest_path ?? raw.contributor?.hf_dest_path ?? raw.contributor?.hfDestPath ?? undefined,};}1239 unmodified linesreturn res.paper;}/*** 将试卷原文件(PDF / 图片)上传到 HuggingFace Storage bucket。* 返回 { fileUrl, destPath } 供写入 exam_paper 表。* 若后端未配置 HF_TOKEN(503)或网络失败,则静默返回 null(不阻断发布流程)。*/public async uploadFileToStorage(file: File,paperId?: string,): Promise<{ fileUrl: string; downloadUrl: string; destPath: string } | null> {const baseUrl = this.getBaseUrl() || '';const endpoint = `${baseUrl}/api/papers/upload-file`;const formData = new FormData();formData.append('file', file);if (paperId) formData.append('paper_id', paperId);try {const res = await fetch(endpoint, {method: 'POST',headers: (() => {// 不要设 Content-Type,让浏览器自动带 boundaryconst h: Record<string, string> = {};const user = (supabaseService as any).getCurrentUser?.();if (user?.accessToken) h['Authorization'] = `Bearer ${user.accessToken}`;return h;})(),body: formData,});if (!res.ok) {const text = await res.text().catch(() => '');console.warn(`[uploadFileToStorage] 上传失败 HTTP ${res.status}:`, text.slice(0, 200));return null;}const data = await res.json();if (data?.success && data?.file_url) {return {fileUrl: data.file_url as string,downloadUrl: (data.download_url || `${data.file_url}?download=true`) as string,destPath: data.dest_path as string,};}} catch (err) {console.warn('[uploadFileToStorage] 网络错误:', err);}return null;}public async uploadPaper(paper: ExamPaper): Promise<ExamPaper> {const res = await this.saveUploadedPaper(paper);return res.paper;}35 unmodified lines}}// 兼具兼容驼峰与下划线的 payload(含 HuggingFace Storage bucket 字段)const payloadForBackend = {...normalizedPaper,full_score: normalizedPaper.fullScore,6 unmodified lineslike_count: normalizedPaper.likeCount,is_featured: normalizedPaper.isFeatured,created_at: normalizedPaper.createdAt,file_url: normalizedPaper.fileUrl,download_url: normalizedPaper.downloadUrl,hf_dest_path: normalizedPaper.hfDestPath,fileUrl: normalizedPaper.fileUrl,downloadUrl: normalizedPaper.downloadUrl,hfDestPath: normalizedPaper.hfDestPath,// 保证 contributor jsonb 也同步携带 file_url / hf_dest_pathcontributor: {...(normalizedPaper.contributor || {}),file_url: normalizedPaper.fileUrl,download_url: normalizedPaper.downloadUrl,hf_dest_path: normalizedPaper.hfDestPath,},};// 1. 依次尝试 FastAPI 接口8 unmodified linesif (res.ok) {const data = await res.json();if (data && (data.id || data.title || data.status === 'success')) {const returnedPaper = normalizePaper(data.data || data);savedPaper = {...returnedPaper,fileUrl: returnedPaper.fileUrl || normalizedPaper.fileUrl,downloadUrl: returnedPaper.downloadUrl || normalizedPaper.downloadUrl,hfDestPath: returnedPaper.hfDestPath || normalizedPaper.hfDestPath,};isPersisted = true;persistedTarget = 'fastapi';endpointUsed = ep;
129 unmodified lines130131132133134135129 unmodified linessourceFormat?: 'pdf' | 'word' | 'image' | 'manual';/** 由 PaddleOCR 识别解析而来时携带的来源信息 */ocrMeta?: OcrSourceMeta;}export interface UserMistake {129 unmodified lines130131132133134135136137138139140141129 unmodified linessourceFormat?: 'pdf' | 'word' | 'image' | 'manual';/** 由 PaddleOCR 识别解析而来时携带的来源信息 */ocrMeta?: OcrSourceMeta;/** HuggingFace Storage bucket 公开 URL(原始 PDF / 图片直链,用于预览与下载) */fileUrl?: string;/** HuggingFace bucket 强制下载直链 */downloadUrl?: string;/** HuggingFace bucket 内部路径,如 "papers/paper-abc123.pdf" */hfDestPath?: string;}export interface UserMistake {
backend/app/__pycache__/main.cpython-310.pyc
backend/app/schemas.py+3
backend/app/unittest/test_paper_ocr.py+56
backend/common/hf_storage.pyAdded+182
backend/common/paper_columns.py+18
backend/common/paper_ocr/router.py+78-3
backend/meloonexam/schemas.py+4
backend/requirements.txt+1
frontend/MeloonExam/src/App.tsx+22-2
frontend/MeloonExam/src/components/OriginalFileViewer.tsx+50-32
frontend/MeloonExam/src/components/PaperUploadModal.tsx+65-10
frontend/MeloonExam/src/services/apiClient.ts+81-2
frontend/MeloonExam/src/types/index.ts+6