dataset_service.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. import subprocess
  60. ds_dir = settings.processed_dir / f"ms_{req.dataset_id.replace('/', '_')}"
  61. ds_dir.mkdir(parents=True, exist_ok=True)
  62. # 用独立进程调用 CLI,完全隔离 FastAPI 事件循环
  63. proc = subprocess.run(
  64. [
  65. "modelscope", "download",
  66. "--dataset", req.dataset_id,
  67. "--local_dir", str(ds_dir),
  68. ],
  69. capture_output=True, text=True, timeout=3600,
  70. )
  71. if proc.returncode != 0:
  72. raise RuntimeError(f"modelscope CLI failed: {proc.stderr}")
  73. # 扫描下载的文件,找训练数据
  74. jsonl_path, record_count = _scan_and_convert_to_jsonl(ds_dir)
  75. else:
  76. from datasets import load_dataset
  77. ds = load_dataset(req.dataset_id)
  78. ds_dir = settings.processed_dir / f"hf_{req.dataset_id.replace('/', '_')}"
  79. ds_dir.mkdir(parents=True, exist_ok=True)
  80. if "train" in ds:
  81. split = ds["train"]
  82. else:
  83. split = ds[list(ds.keys())[0]]
  84. output_path = ds_dir / "data.jsonl"
  85. with open(output_path, "w", encoding="utf-8") as f:
  86. for item in split:
  87. f.write(json.dumps(item, ensure_ascii=False) + "\n")
  88. jsonl_path = output_path
  89. record_count = len(split) if hasattr(split, "__len__") else 0
  90. record = DatasetRecord(
  91. id=str(uuid.uuid4()),
  92. name=req.dataset_id,
  93. format="jsonl",
  94. record_count=record_count,
  95. file_path=str(jsonl_path),
  96. created_at=datetime.utcnow(),
  97. )
  98. async with async_session() as session:
  99. session.add(record)
  100. await session.commit()
  101. logger.info(f"Downloaded dataset: {req.dataset_id} ({record_count} records, source={'ModelScope' if req.use_modelscope else 'HuggingFace'})")
  102. return DatasetDownloadResponse(dataset_id=req.dataset_id, status="completed", path=str(jsonl_path))
  103. except Exception as e:
  104. logger.error(f"Dataset download failed: {e}")
  105. return DatasetDownloadResponse(dataset_id=req.dataset_id, status="failed", error=str(e))
  106. def _scan_and_convert_to_jsonl(ds_dir: Path) -> tuple[Path, int]:
  107. """扫描 CLI 下载的数据集目录,找训练数据文件并转为 JSONL。"""
  108. # 找所有可能的数据文件
  109. data_files = []
  110. for ext in ("*.jsonl", "*.json", "*.csv"):
  111. data_files.extend(ds_dir.rglob(ext))
  112. # 过滤掉元数据文件
  113. data_files = [f for f in data_files if f.name not in META_FILENAMES]
  114. if not data_files:
  115. raise RuntimeError(f"No dataset files found in {ds_dir}")
  116. jsonl_path = ds_dir / "data.jsonl"
  117. record_count = 0
  118. with open(jsonl_path, "w", encoding="utf-8") as out:
  119. for data_file in data_files:
  120. if data_file.suffix == ".jsonl":
  121. with open(data_file, "r", encoding="utf-8") as f:
  122. for line in f:
  123. line = line.strip()
  124. if line:
  125. out.write(line + "\n")
  126. record_count += 1
  127. elif data_file.suffix == ".json":
  128. try:
  129. with open(data_file, "r", encoding="utf-8") as f:
  130. data = json.load(f)
  131. if isinstance(data, list):
  132. for item in data:
  133. out.write(json.dumps(item, ensure_ascii=False) + "\n")
  134. record_count += 1
  135. elif isinstance(data, dict):
  136. out.write(json.dumps(data, ensure_ascii=False) + "\n")
  137. record_count += 1
  138. except Exception:
  139. pass
  140. elif data_file.suffix == ".csv":
  141. import csv
  142. with open(data_file, "r", encoding="utf-8") as f:
  143. reader = csv.DictReader(f)
  144. for row in reader:
  145. out.write(json.dumps(dict(row), ensure_ascii=False) + "\n")
  146. record_count += 1
  147. return jsonl_path, record_count
  148. async def upload_dataset(file: UploadFile) -> dict[str, Any]:
  149. """保存上传文件并写入数据库。"""
  150. upload_dir = settings.uploads_dir
  151. upload_dir.mkdir(parents=True, exist_ok=True)
  152. safe_name = file.filename or "unknown"
  153. file_path = upload_dir / safe_name
  154. if file_path.exists():
  155. file_path = upload_dir / f"{uuid.uuid4().hex}_{safe_name}"
  156. content = await file.read()
  157. file_path.write_bytes(content)
  158. fmt = _detect_format(safe_name)
  159. record_count = _count_records(file_path, fmt)
  160. record_id = str(uuid.uuid4())
  161. record = DatasetRecord(
  162. id=record_id,
  163. name=safe_name,
  164. format=fmt,
  165. record_count=record_count,
  166. file_path=str(file_path),
  167. created_at=datetime.utcnow(),
  168. )
  169. async with async_session() as session:
  170. session.add(record)
  171. await session.commit()
  172. logger.info(f"Uploaded dataset: {safe_name} ({record_count} records, format={fmt})")
  173. return {
  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": record.created_at.isoformat(),
  180. }
  181. def _format_value(value) -> str:
  182. """将复杂值格式化为可读字符串。"""
  183. if isinstance(value, (dict, list)):
  184. return json.dumps(value, ensure_ascii=False, indent=2)
  185. return str(value)
  186. def _is_sharegpt_format(records: list[dict]) -> bool:
  187. """检测是否为 ShareGPT 格式。"""
  188. if not records:
  189. return False
  190. first = records[0]
  191. if "conversations" in first and isinstance(first["conversations"], list):
  192. if len(first["conversations"]) > 0 and isinstance(first["conversations"][0], dict):
  193. conv = first["conversations"][0]
  194. return "from" in conv and "value" in conv
  195. return False
  196. def _flatten_sharegpt(records: list[dict]) -> tuple[list[dict], list[str]]:
  197. """将 ShareGPT 格式展平为 input/output 列。"""
  198. flat_rows = []
  199. for row in records:
  200. conversations = row.get("conversations", [])
  201. for i in range(0, len(conversations) - 1, 2):
  202. user_turn = conversations[i]
  203. assistant_turn = conversations[i + 1] if i + 1 < len(conversations) else None
  204. if user_turn.get("from") in ("human", "user"):
  205. input_text = str(user_turn.get("value", ""))
  206. output_text = str(assistant_turn.get("value", "")) if assistant_turn else ""
  207. else:
  208. input_text = str(assistant_turn.get("value", "")) if assistant_turn else ""
  209. output_text = str(user_turn.get("value", ""))
  210. if len(input_text) > 500:
  211. input_text = input_text[:500] + "..."
  212. if len(output_text) > 500:
  213. output_text = output_text[:500] + "..."
  214. flat_rows.append({"input": input_text, "output": output_text})
  215. return flat_rows, ["input", "output"]
  216. async def preview_dataset(dataset_id: str, rows: int = 10) -> dict[str, Any]:
  217. """预览数据集前 N 行。"""
  218. async with async_session() as session:
  219. from sqlalchemy import select
  220. result = await session.execute(select(DatasetRecord).where(DatasetRecord.id == dataset_id))
  221. record = result.scalar_one_or_none()
  222. if not record:
  223. return {"total_records": 0, "preview_rows": [], "columns": []}
  224. file_path = Path(record.file_path)
  225. if not file_path.exists():
  226. return {"total_records": 0, "preview_rows": [], "columns": []}
  227. fmt = record.format
  228. preview_data = _read_records(file_path, fmt, rows)
  229. # 检测是否为 ShareGPT 格式,如果是则展平为 input/output 列
  230. if _is_sharegpt_format(preview_data):
  231. preview_data, columns = _flatten_sharegpt(preview_data)
  232. else:
  233. columns = list(preview_data[0].keys()) if preview_data else []
  234. return {
  235. "total_records": record.record_count,
  236. "preview_rows": [
  237. {
  238. "row_index": i,
  239. "data": {k: _format_value(v) for k, v in row.items()},
  240. }
  241. for i, row in enumerate(preview_data)
  242. ],
  243. "columns": columns,
  244. }
  245. async def validate_dataset(dataset_id: str) -> dict[str, Any]:
  246. """校验数据集格式和 Schema。"""
  247. async with async_session() as session:
  248. from sqlalchemy import select
  249. result = await session.execute(select(DatasetRecord).where(DatasetRecord.id == dataset_id))
  250. record = result.scalar_one_or_none()
  251. if not record:
  252. return {"is_valid": False, "errors": ["Dataset not found"], "warnings": []}
  253. file_path = Path(record.file_path)
  254. if not file_path.exists():
  255. return {"is_valid": False, "errors": ["File not found"], "warnings": []}
  256. errors = []
  257. warnings = []
  258. fmt = record.format
  259. if fmt not in ("jsonl", "csv", "json", "parquet"):
  260. errors.append(f"Unsupported format: {fmt}")
  261. try:
  262. preview = _read_records(file_path, fmt, 5)
  263. if not preview:
  264. warnings.append("Dataset appears to be empty")
  265. else:
  266. first = preview[0]
  267. has_sft_fields = any(k in first for k in ("instruction", "prompt", "text", "input", "output", "completion"))
  268. if not has_sft_fields:
  269. warnings.append(f"No common SFT fields found. Keys: {list(first.keys())}")
  270. except Exception as e:
  271. errors.append(f"Failed to read file: {str(e)}")
  272. return {"is_valid": len(errors) == 0, "errors": errors, "warnings": warnings}
  273. async def list_datasets() -> list[dict[str, Any]]:
  274. """列出所有已上传数据集。"""
  275. async with async_session() as session:
  276. from sqlalchemy import select
  277. result = await session.execute(select(DatasetRecord).order_by(DatasetRecord.created_at.desc()))
  278. records = result.scalars().all()
  279. return [
  280. {
  281. "id": r.id,
  282. "name": r.name,
  283. "format": r.format,
  284. "record_count": r.record_count,
  285. "file_path": r.file_path,
  286. "created_at": r.created_at.isoformat(),
  287. }
  288. for r in records
  289. ]
  290. async def delete_dataset(dataset_id: str) -> dict[str, Any]:
  291. """删除数据集。"""
  292. async with async_session() as session:
  293. from sqlalchemy import select
  294. result = await session.execute(select(DatasetRecord).where(DatasetRecord.id == dataset_id))
  295. record = result.scalar_one_or_none()
  296. if record:
  297. file_path = Path(record.file_path)
  298. if file_path.exists():
  299. file_path.unlink()
  300. await session.delete(record)
  301. await session.commit()
  302. logger.info(f"Deleted dataset: {record.name}")
  303. return {"status": "deleted"}
  304. def _detect_format(filename: str) -> str:
  305. ext = Path(filename).suffix.lower().lstrip(".")
  306. if ext in ("jsonl", "csv", "parquet", "json"):
  307. return ext
  308. return "unknown"
  309. def _count_records(file_path: Path, fmt: str) -> int:
  310. try:
  311. if fmt == "jsonl":
  312. return sum(1 for line in open(file_path, encoding="utf-8") if line.strip())
  313. elif fmt == "json":
  314. with open(file_path, encoding="utf-8") as f:
  315. data = json.load(f)
  316. return len(data) if isinstance(data, list) else 1
  317. elif fmt == "csv":
  318. import csv
  319. with open(file_path, encoding="utf-8") as f:
  320. return sum(1 for _ in csv.reader(f)) - 1
  321. elif fmt == "parquet":
  322. import pandas as pd
  323. return len(pd.read_parquet(file_path))
  324. except Exception:
  325. pass
  326. return 0
  327. def _read_records(file_path: Path, fmt: str, n: int) -> list[dict]:
  328. if fmt == "jsonl":
  329. records = []
  330. with open(file_path, encoding="utf-8") as f:
  331. for i, line in enumerate(f):
  332. if i >= n:
  333. break
  334. line = line.strip()
  335. if line:
  336. records.append(json.loads(line))
  337. return records
  338. elif fmt == "json":
  339. with open(file_path, encoding="utf-8") as f:
  340. data = json.load(f)
  341. return data[:n] if isinstance(data, list) else [data]
  342. elif fmt == "csv":
  343. import csv
  344. with open(file_path, encoding="utf-8") as f:
  345. reader = csv.DictReader(f)
  346. return [dict(row) for i, row in enumerate(reader) if i < n]
  347. elif fmt == "parquet":
  348. import pandas as pd
  349. df = pd.read_parquet(file_path)
  350. return df.head(n).to_dict(orient="records")
  351. return []