dataset_service.py 17 KB

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