dataset_service.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. import asyncio
  2. import json
  3. import uuid
  4. from datetime import datetime
  5. from pathlib import Path
  6. from typing import Any
  7. from fastapi import UploadFile
  8. from app.config import get_settings
  9. from app.core.db import async_session, DatasetRecord
  10. from app.core.logging import logger
  11. from app.schemas.dataset import DatasetDownloadRequest, DatasetDownloadResponse
  12. settings = get_settings()
  13. # Known metadata filenames that are NOT training data
  14. META_FILENAMES = frozenset({
  15. "configuration.json", "configuration.yaml", "README.md",
  16. ".mdl", ".msc", ".mv", "model_index.json", "generation_config.json",
  17. "special_tokens_map.json", "tokenizer_config.json",
  18. "added_tokens.json", "vocab.json", "merges.txt",
  19. "config.json", "preprocessor_config.json",
  20. })
  21. # File size threshold: files smaller than this (bytes) are likely metadata
  22. META_SIZE_THRESHOLD = 500
  23. def _is_training_data_file(path: Path) -> bool:
  24. """判断文件是否可能是训练数据文件(而非配置/元数据)。"""
  25. if path.suffix in (".jsonl", ".parquet", ".csv"):
  26. return True
  27. if path.suffix == ".json":
  28. if path.name in META_FILENAMES:
  29. return False
  30. # 小 JSON 文件通常是配置
  31. if path.stat().st_size < META_SIZE_THRESHOLD:
  32. return False
  33. # 尝试读取首行判断格式
  34. try:
  35. first_line = path.read_text(encoding="utf-8", errors="ignore").splitlines()[0].strip()
  36. obj = json.loads(first_line)
  37. # 如果有 input/output/conversation/instruction 等字段,则是训练数据
  38. if isinstance(obj, dict):
  39. data_keys = {"input", "output", "conversations", "instruction", "prompt",
  40. "text", "completion", "source", "target", "query", "response"}
  41. if data_keys & set(obj.keys()):
  42. return True
  43. return True # 大 JSON 文件默认是数据
  44. except Exception:
  45. return False
  46. # 无后缀文件:尝试读取判断是否为 JSON/JSONL
  47. if not path.suffix:
  48. try:
  49. first_line = path.read_text(encoding="utf-8", errors="ignore").splitlines()[0].strip()
  50. json.loads(first_line)
  51. return True
  52. except Exception:
  53. return False
  54. return False
  55. async def download_dataset(req: DatasetDownloadRequest) -> DatasetDownloadResponse:
  56. """从 HuggingFace 或 ModelScope 下载数据集。"""
  57. try:
  58. if req.use_modelscope:
  59. ds_dir, jsonl_path, record_count = await asyncio.to_thread(_download_modelscope_dataset, req.dataset_id)
  60. else:
  61. from datasets import load_dataset
  62. ds = load_dataset(req.dataset_id)
  63. ds_dir = settings.processed_dir / f"hf_{req.dataset_id.replace('/', '_')}"
  64. ds_dir.mkdir(parents=True, exist_ok=True)
  65. if "train" in ds:
  66. split = ds["train"]
  67. else:
  68. split = ds[list(ds.keys())[0]]
  69. output_path = ds_dir / "data.jsonl"
  70. with open(output_path, "w", encoding="utf-8") as f:
  71. for item in split:
  72. f.write(json.dumps(item, ensure_ascii=False) + "\n")
  73. jsonl_path = output_path
  74. record_count = len(split) if hasattr(split, "__len__") else 0
  75. record = DatasetRecord(
  76. id=str(uuid.uuid4()),
  77. name=req.dataset_id,
  78. format="jsonl",
  79. record_count=record_count,
  80. file_path=str(jsonl_path),
  81. created_at=datetime.utcnow(),
  82. )
  83. async with async_session() as session:
  84. session.add(record)
  85. await session.commit()
  86. logger.info(f"Downloaded dataset: {req.dataset_id} ({record_count} records, source={'ModelScope' if req.use_modelscope else 'HuggingFace'})")
  87. return DatasetDownloadResponse(dataset_id=req.dataset_id, status="completed", path=str(jsonl_path))
  88. except Exception as e:
  89. logger.error(f"Dataset download failed: {e}")
  90. return DatasetDownloadResponse(dataset_id=req.dataset_id, status="failed", error=str(e))
  91. def _download_modelscope_dataset(dataset_id: str) -> tuple[Path, Path, int]:
  92. """用 modelscope CLI 下载数据集,完全绕过 datasets 库,避免版本兼容问题。"""
  93. import subprocess
  94. ds_dir = settings.processed_dir / f"ms_{dataset_id.replace('/', '_')}"
  95. ds_dir.mkdir(parents=True, exist_ok=True)
  96. # 使用 CLI 方式下载,避免 snapshot_download API 的路径问题
  97. cmd = ["modelscope", "download", "--dataset", dataset_id, "--local_dir", str(ds_dir)]
  98. logger.info(f"Running: {' '.join(cmd)}")
  99. proc = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
  100. if proc.returncode != 0:
  101. logger.error(f"ModelScope CLI download failed (code={proc.returncode}): {proc.stderr[:500]}")
  102. raise RuntimeError(f"ModelScope download failed: {proc.stderr[:500]}")
  103. # 扫描下载目录中的所有文件
  104. all_files = [p for p in ds_dir.rglob("*") if p.is_file()]
  105. logger.info(f"ModelScope CLI downloaded {len(all_files)} files to {ds_dir}")
  106. # 识别训练数据文件
  107. data_files = [f for f in all_files if _is_training_data_file(f)]
  108. if not data_files:
  109. fallback = [f for f in all_files if f.suffix in (".json", ".jsonl") and f.name not in META_FILENAMES]
  110. logger.warning(f"No training data files found in {dataset_id}. "
  111. f"Available JSON files: {[f.name for f in fallback]}")
  112. if fallback:
  113. data_files = fallback
  114. else:
  115. # 如果还是没有,列出所有文件供排查
  116. logger.error(f"All downloaded files: {[str(f.relative_to(ds_dir)) for f in all_files]}")
  117. raise ValueError(f"No JSON/JSONL data files found in dataset {dataset_id}. "
  118. f"Available files: {[f.name for f in all_files]}")
  119. # 优先取 train / data 开头的文件
  120. target = None
  121. for name in ("train.jsonl", "train.json", "data.jsonl", "data.json"):
  122. for f in data_files:
  123. if f.name == name:
  124. target = f
  125. break
  126. if target:
  127. break
  128. if not target:
  129. # 优先取数据量最大的文件
  130. target = sorted(data_files, key=lambda f: f.stat().st_size, reverse=True)[0]
  131. logger.info(f"Selected data file: {target} (size={target.stat().st_size})")
  132. # 读取并统一转为 JSONL
  133. jsonl_path = ds_dir / "data.jsonl"
  134. record_count = 0
  135. content = target.read_text(encoding="utf-8")
  136. if target.suffix == ".jsonl" or not target.suffix:
  137. # JSONL 或无后缀文件:尝试逐行解析
  138. records = []
  139. for line in content.splitlines():
  140. line = line.strip()
  141. if not line:
  142. continue
  143. try:
  144. records.append(json.loads(line))
  145. except json.JSONDecodeError:
  146. # 如果逐行解析失败,尝试整体解析(可能是 JSON 数组)
  147. records = json.loads(content)
  148. if not isinstance(records, list):
  149. records = [records]
  150. break
  151. else:
  152. records = json.loads(content)
  153. if not isinstance(records, list):
  154. records = [records]
  155. with open(jsonl_path, "w", encoding="utf-8") as f:
  156. for item in records:
  157. f.write(json.dumps(item, ensure_ascii=False) + "\n")
  158. record_count += 1
  159. return ds_dir, jsonl_path, record_count
  160. async def upload_dataset(file: UploadFile) -> dict[str, Any]:
  161. """保存上传文件并写入数据库。"""
  162. upload_dir = settings.uploads_dir
  163. upload_dir.mkdir(parents=True, exist_ok=True)
  164. safe_name = file.filename or "unknown"
  165. file_path = upload_dir / safe_name
  166. if file_path.exists():
  167. file_path = upload_dir / f"{uuid.uuid4().hex}_{safe_name}"
  168. content = await file.read()
  169. file_path.write_bytes(content)
  170. fmt = _detect_format(safe_name)
  171. record_count = _count_records(file_path, fmt)
  172. record_id = str(uuid.uuid4())
  173. record = DatasetRecord(
  174. id=record_id,
  175. name=safe_name,
  176. format=fmt,
  177. record_count=record_count,
  178. file_path=str(file_path),
  179. created_at=datetime.utcnow(),
  180. )
  181. async with async_session() as session:
  182. session.add(record)
  183. await session.commit()
  184. logger.info(f"Uploaded dataset: {safe_name} ({record_count} records, format={fmt})")
  185. return {
  186. "id": record_id,
  187. "name": safe_name,
  188. "format": fmt,
  189. "record_count": record_count,
  190. "file_path": str(file_path),
  191. "created_at": record.created_at.isoformat(),
  192. }
  193. def _format_value(value) -> str:
  194. """将复杂值格式化为可读字符串。"""
  195. if isinstance(value, (dict, list)):
  196. return json.dumps(value, ensure_ascii=False, indent=2)
  197. return str(value)
  198. def _is_sharegpt_format(records: list[dict]) -> bool:
  199. """检测是否为 ShareGPT 格式。"""
  200. if not records:
  201. return False
  202. first = records[0]
  203. if "conversations" in first and isinstance(first["conversations"], list):
  204. if len(first["conversations"]) > 0 and isinstance(first["conversations"][0], dict):
  205. conv = first["conversations"][0]
  206. return "from" in conv and "value" in conv
  207. return False
  208. def _flatten_sharegpt(records: list[dict]) -> tuple[list[dict], list[str]]:
  209. """将 ShareGPT 格式展平为 input/output 列。"""
  210. flat_rows = []
  211. for row in records:
  212. conversations = row.get("conversations", [])
  213. for i in range(0, len(conversations) - 1, 2):
  214. user_turn = conversations[i]
  215. assistant_turn = conversations[i + 1] if i + 1 < len(conversations) else None
  216. if user_turn.get("from") in ("human", "user"):
  217. input_text = str(user_turn.get("value", ""))
  218. output_text = str(assistant_turn.get("value", "")) if assistant_turn else ""
  219. else:
  220. input_text = str(assistant_turn.get("value", "")) if assistant_turn else ""
  221. output_text = str(user_turn.get("value", ""))
  222. if len(input_text) > 500:
  223. input_text = input_text[:500] + "..."
  224. if len(output_text) > 500:
  225. output_text = output_text[:500] + "..."
  226. flat_rows.append({"input": input_text, "output": output_text})
  227. return flat_rows, ["input", "output"]
  228. async def preview_dataset(dataset_id: str, rows: int = 10) -> dict[str, Any]:
  229. """预览数据集前 N 行。"""
  230. async with async_session() as session:
  231. from sqlalchemy import select
  232. result = await session.execute(select(DatasetRecord).where(DatasetRecord.id == dataset_id))
  233. record = result.scalar_one_or_none()
  234. if not record:
  235. return {"total_records": 0, "preview_rows": [], "columns": []}
  236. file_path = Path(record.file_path)
  237. if not file_path.exists():
  238. return {"total_records": 0, "preview_rows": [], "columns": []}
  239. fmt = record.format
  240. preview_data = _read_records(file_path, fmt, rows)
  241. # 检测是否为 ShareGPT 格式,如果是则展平为 input/output 列
  242. if _is_sharegpt_format(preview_data):
  243. preview_data, columns = _flatten_sharegpt(preview_data)
  244. else:
  245. columns = list(preview_data[0].keys()) if preview_data else []
  246. return {
  247. "total_records": record.record_count,
  248. "preview_rows": [
  249. {
  250. "row_index": i,
  251. "data": {k: _format_value(v) for k, v in row.items()},
  252. }
  253. for i, row in enumerate(preview_data)
  254. ],
  255. "columns": columns,
  256. }
  257. async def validate_dataset(dataset_id: str) -> dict[str, Any]:
  258. """校验数据集格式和 Schema。"""
  259. async with async_session() as session:
  260. from sqlalchemy import select
  261. result = await session.execute(select(DatasetRecord).where(DatasetRecord.id == dataset_id))
  262. record = result.scalar_one_or_none()
  263. if not record:
  264. return {"is_valid": False, "errors": ["Dataset not found"], "warnings": []}
  265. file_path = Path(record.file_path)
  266. if not file_path.exists():
  267. return {"is_valid": False, "errors": ["File not found"], "warnings": []}
  268. errors = []
  269. warnings = []
  270. fmt = record.format
  271. if fmt not in ("jsonl", "csv", "json", "parquet"):
  272. errors.append(f"Unsupported format: {fmt}")
  273. try:
  274. preview = _read_records(file_path, fmt, 5)
  275. if not preview:
  276. warnings.append("Dataset appears to be empty")
  277. else:
  278. first = preview[0]
  279. has_sft_fields = any(k in first for k in ("instruction", "prompt", "text", "input", "output", "completion"))
  280. if not has_sft_fields:
  281. warnings.append(f"No common SFT fields found. Keys: {list(first.keys())}")
  282. except Exception as e:
  283. errors.append(f"Failed to read file: {str(e)}")
  284. return {"is_valid": len(errors) == 0, "errors": errors, "warnings": warnings}
  285. async def list_datasets() -> list[dict[str, Any]]:
  286. """列出所有已上传数据集。"""
  287. async with async_session() as session:
  288. from sqlalchemy import select
  289. result = await session.execute(select(DatasetRecord).order_by(DatasetRecord.created_at.desc()))
  290. records = result.scalars().all()
  291. return [
  292. {
  293. "id": r.id,
  294. "name": r.name,
  295. "format": r.format,
  296. "record_count": r.record_count,
  297. "file_path": r.file_path,
  298. "created_at": r.created_at.isoformat(),
  299. }
  300. for r in records
  301. ]
  302. async def delete_dataset(dataset_id: str) -> dict[str, Any]:
  303. """删除数据集。"""
  304. async with async_session() as session:
  305. from sqlalchemy import select
  306. result = await session.execute(select(DatasetRecord).where(DatasetRecord.id == dataset_id))
  307. record = result.scalar_one_or_none()
  308. if record:
  309. file_path = Path(record.file_path)
  310. if file_path.exists():
  311. file_path.unlink()
  312. await session.delete(record)
  313. await session.commit()
  314. logger.info(f"Deleted dataset: {record.name}")
  315. return {"status": "deleted"}
  316. def _detect_format(filename: str) -> str:
  317. ext = Path(filename).suffix.lower().lstrip(".")
  318. if ext in ("jsonl", "csv", "parquet", "json"):
  319. return ext
  320. return "unknown"
  321. def _count_records(file_path: Path, fmt: str) -> int:
  322. try:
  323. if fmt == "jsonl":
  324. return sum(1 for line in open(file_path, encoding="utf-8") if line.strip())
  325. elif fmt == "json":
  326. with open(file_path, encoding="utf-8") as f:
  327. data = json.load(f)
  328. return len(data) if isinstance(data, list) else 1
  329. elif fmt == "csv":
  330. import csv
  331. with open(file_path, encoding="utf-8") as f:
  332. return sum(1 for _ in csv.reader(f)) - 1
  333. elif fmt == "parquet":
  334. import pandas as pd
  335. return len(pd.read_parquet(file_path))
  336. except Exception:
  337. pass
  338. return 0
  339. def _read_records(file_path: Path, fmt: str, n: int) -> list[dict]:
  340. if fmt == "jsonl":
  341. records = []
  342. with open(file_path, encoding="utf-8") as f:
  343. for i, line in enumerate(f):
  344. if i >= n:
  345. break
  346. line = line.strip()
  347. if line:
  348. records.append(json.loads(line))
  349. return records
  350. elif fmt == "json":
  351. with open(file_path, encoding="utf-8") as f:
  352. data = json.load(f)
  353. return data[:n] if isinstance(data, list) else [data]
  354. elif fmt == "csv":
  355. import csv
  356. with open(file_path, encoding="utf-8") as f:
  357. reader = csv.DictReader(f)
  358. return [dict(row) for i, row in enumerate(reader) if i < n]
  359. elif fmt == "parquet":
  360. import pandas as pd
  361. df = pd.read_parquet(file_path)
  362. return df.head(n).to_dict(orient="records")
  363. return []