dataset_service.py 16 KB

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