-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathgeneration_api.py
More file actions
613 lines (521 loc) · 19.3 KB
/
generation_api.py
File metadata and controls
613 lines (521 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
import uuid
from typing import cast
from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks
from sqlalchemy import select, func, delete
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.db.models.data_synthesis import (
save_synthesis_task,
DataSynthInstance,
DataSynthesisFileInstance,
DataSynthesisChunkInstance,
SynthesisData,
)
from app.db.models.dataset_management import DatasetFiles
from app.db.session import get_db
from app.module.generation.schema.generation import (
CreateSynthesisTaskRequest,
DataSynthesisTaskItem,
PagedDataSynthesisTaskResponse,
SynthesisType,
DataSynthesisFileTaskItem,
PagedDataSynthesisFileTaskResponse,
DataSynthesisChunkItem,
PagedDataSynthesisChunkResponse,
SynthesisDataItem,
SynthesisDataUpdateRequest,
BatchDeleteSynthesisDataRequest,
)
from app.module.generation.service.export_service import SynthesisDatasetExporter, SynthesisExportError
from app.module.generation.service.generation_service import GenerationService
from app.module.generation.service.prompt import get_prompt
from app.module.shared.schema import StandardResponse
router = APIRouter(
prefix="/gen",
tags=["gen"]
)
logger = get_logger(__name__)
@router.post("/task", response_model=StandardResponse[DataSynthesisTaskItem])
async def create_synthesis_task(
request: CreateSynthesisTaskRequest,
background_tasks: BackgroundTasks,
db: AsyncSession = Depends(get_db),
):
"""创建数据合成任务"""
# 先根据 source_file_id 在 DatasetFiles 中查出已有文件信息
file_ids = request.source_file_id or []
dataset_files = []
if file_ids:
ds_result = await db.execute(
select(DatasetFiles).where(DatasetFiles.id.in_(file_ids))
)
dataset_files = ds_result.scalars().all()
# 保存任务到数据库
request.source_file_id = [str(f.id) for f in dataset_files]
synthesis_task = await save_synthesis_task(db, request)
# 将已有的 DatasetFiles 记录保存到 t_data_synthesis_file_instances
synth_files = []
for f in dataset_files:
file_instance = DataSynthesisFileInstance(
id=str(uuid.uuid4()), # 使用新的 UUID 作为文件任务记录的主键,避免与 DatasetFiles 主键冲突
synthesis_instance_id=synthesis_task.id,
file_name=f.file_name,
source_file_id=str(f.id),
status="pending",
total_chunks=0,
processed_chunks=0,
created_by="system",
updated_by="system",
)
synth_files.append(file_instance)
if dataset_files:
db.add_all(synth_files)
await db.commit()
generation_service = GenerationService(db)
# 异步处理任务:只传任务 ID,后台任务中使用新的 DB 会话重新加载任务对象
background_tasks.add_task(generation_service.process_task, synthesis_task.id)
# 将 ORM 对象包装成 DataSynthesisTaskItem,兼容新字段从 synth_config 还原
task_item = DataSynthesisTaskItem(
id=synthesis_task.id,
name=synthesis_task.name,
description=synthesis_task.description,
status=synthesis_task.status,
synthesis_type=synthesis_task.synth_type,
total_files=synthesis_task.total_files,
created_at=synthesis_task.created_at,
updated_at=synthesis_task.updated_at,
created_by=synthesis_task.created_by,
updated_by=synthesis_task.updated_by,
)
return StandardResponse(
code=200,
message="success",
data=task_item,
)
@router.get("/task/{task_id}", response_model=StandardResponse[DataSynthesisTaskItem])
async def get_synthesis_task(
task_id: str,
db: AsyncSession = Depends(get_db)
):
"""获取数据合成任务详情"""
synthesis_task = await db.get(DataSynthInstance, task_id)
if not synthesis_task:
raise HTTPException(status_code=404, detail="Synthesis task not found")
task_item = DataSynthesisTaskItem(
id=synthesis_task.id,
name=synthesis_task.name,
description=synthesis_task.description,
status=synthesis_task.status,
synthesis_type=synthesis_task.synth_type,
total_files=synthesis_task.total_files,
created_at=synthesis_task.created_at,
updated_at=synthesis_task.updated_at,
created_by=synthesis_task.created_by,
updated_by=synthesis_task.updated_by,
)
return StandardResponse(
code=200,
message="success",
data=task_item,
)
@router.get("/tasks", response_model=StandardResponse[PagedDataSynthesisTaskResponse], status_code=200)
async def list_synthesis_tasks(
page: int = 1,
page_size: int = 10,
synthesis_type: str | None = None,
status: str | None = None,
name: str | None = None,
db: AsyncSession = Depends(get_db)
):
"""分页列出所有数据合成任务,默认按创建时间倒序"""
query = select(DataSynthInstance)
if synthesis_type:
query = query.filter(DataSynthInstance.synth_type == synthesis_type)
if status:
query = query.filter(DataSynthInstance.status == status)
if name:
query = query.filter(DataSynthInstance.name.like(f"%{name}%"))
# 默认按创建时间倒序排列
query = query.order_by(DataSynthInstance.created_at.desc())
count_q = select(func.count()).select_from(query.subquery())
total = (await db.execute(count_q)).scalar_one()
if page < 1:
page = 1
if page_size < 1:
page_size = 10
result = await db.execute(query.offset((page - 1) * page_size).limit(page_size))
rows = result.scalars().all()
task_items: list[DataSynthesisTaskItem] = []
for row in rows:
synth_cfg = getattr(row, "synth_config", {}) or {}
text_split_cfg = synth_cfg.get("text_split_config") or {}
synthesis_cfg = synth_cfg.get("synthesis_config") or {}
source_file_ids = synth_cfg.get("source_file_id") or []
model_id = synth_cfg.get("model_id")
result_location = synth_cfg.get("result_data_location")
task_items.append(
DataSynthesisTaskItem(
id=str(row.id),
name=str(row.name),
description=cast(str | None, row.description),
status=cast(str | None, row.status),
synthesis_type=str(row.synth_type),
model_id=model_id or "",
progress=int(cast(int, row.progress)),
result_data_location=result_location,
text_split_config=text_split_cfg,
synthesis_config=synthesis_cfg,
source_file_id=list(source_file_ids),
total_files=int(cast(int, row.total_files)),
processed_files=int(cast(int, row.processed_files)),
total_chunks=int(cast(int, row.total_chunks)),
processed_chunks=int(cast(int, row.processed_chunks)),
total_synthesis_data=int(cast(int, row.total_synth_data)),
created_at=row.created_at,
updated_at=row.updated_at,
created_by=row.created_by,
updated_by=row.updated_by,
)
)
paged = PagedDataSynthesisTaskResponse(
content=task_items,
totalElements=total,
totalPages=(total + page_size - 1) // page_size,
page=page,
size=page_size,
)
return StandardResponse(
code=200,
message="Success",
data=paged,
)
@router.delete("/task/{task_id}", response_model=StandardResponse)
async def delete_synthesis_task(
task_id: str,
db: AsyncSession = Depends(get_db)
):
"""删除数据合成任务"""
task = await db.get(DataSynthInstance, task_id)
if not task:
raise HTTPException(status_code=404, detail="Synthesis task not found")
# 1. 删除与该任务相关的 SynthesisData、Chunk、File 记录
# 先查出所有文件任务 ID
file_result = await db.execute(
select(DataSynthesisFileInstance.id).where(
DataSynthesisFileInstance.synthesis_instance_id == task_id
)
)
file_ids = [row[0] for row in file_result.all()]
if file_ids:
# 删除 SynthesisData(根据文件任务ID)
await db.execute(delete(SynthesisData).where(
SynthesisData.synthesis_file_instance_id.in_(file_ids)
)
)
# 删除 Chunk 记录
await db.execute(delete(DataSynthesisChunkInstance).where(
DataSynthesisChunkInstance.synthesis_file_instance_id.in_(file_ids)
)
)
# 删除文件任务记录
await db.execute(delete(DataSynthesisFileInstance).where(
DataSynthesisFileInstance.id.in_(file_ids)
)
)
# 2. 删除任务本身
await db.delete(task)
await db.commit()
return StandardResponse(
code=200,
message="success",
data=None,
)
@router.delete("/task/{task_id}/{file_id}", response_model=StandardResponse)
async def delete_synthesis_file_task(
task_id: str,
file_id: str,
db: AsyncSession = Depends(get_db)
):
"""删除数据合成任务中的文件任务,同时刷新任务表中的文件/切片数量"""
# 先获取任务和文件任务记录
task = await db.get(DataSynthInstance, task_id)
if not task:
raise HTTPException(status_code=404, detail="Synthesis task not found")
file_task = await db.get(DataSynthesisFileInstance, file_id)
if not file_task:
raise HTTPException(status_code=404, detail="Synthesis file task not found")
# 删除 SynthesisData(根据文件任务ID)
await db.execute(
delete(SynthesisData).where(
SynthesisData.synthesis_file_instance_id == file_id
)
)
# 删除 Chunk 记录
await db.execute(delete(DataSynthesisChunkInstance).where(
DataSynthesisChunkInstance.synthesis_file_instance_id == file_id
)
)
# 删除文件任务记录
await db.execute(
delete(DataSynthesisFileInstance).where(
DataSynthesisFileInstance.id == file_id
)
)
# 刷新任务级别统计字段:总文件数、总文本块数、已处理文本块数
if task.total_files and task.total_files > 0:
task.total_files -= 1
if task.total_files < 0:
task.total_files = 0
await db.commit()
await db.refresh(task)
return StandardResponse(
code=200,
message="success",
data=None,
)
@router.get("/prompt", response_model=StandardResponse[str])
async def get_prompt_by_type(
synth_type: SynthesisType,
):
prompt = get_prompt(synth_type)
return StandardResponse(
code=200,
message="Success",
data=prompt,
)
@router.get("/task/{task_id}/files", response_model=StandardResponse[PagedDataSynthesisFileTaskResponse])
async def list_synthesis_file_tasks(
task_id: str,
page: int = 1,
page_size: int = 10,
db: AsyncSession = Depends(get_db),
):
"""分页获取某个数据合成任务下的文件任务列表"""
# 先校验任务是否存在
task = await db.get(DataSynthInstance, task_id)
if not task:
raise HTTPException(status_code=404, detail="Synthesis task not found")
base_query = select(DataSynthesisFileInstance).where(
DataSynthesisFileInstance.synthesis_instance_id == task_id
)
count_q = select(func.count()).select_from(base_query.subquery())
total = (await db.execute(count_q)).scalar_one()
if page < 1:
page = 1
if page_size < 1:
page_size = 10
result = await db.execute(
base_query.offset((page - 1) * page_size).limit(page_size)
)
rows = result.scalars().all()
file_items = [
DataSynthesisFileTaskItem(
id=row.id,
synthesis_instance_id=row.synthesis_instance_id,
file_name=row.file_name,
source_file_id=row.source_file_id,
status=row.status,
total_chunks=row.total_chunks,
processed_chunks=row.processed_chunks,
created_at=row.created_at,
updated_at=row.updated_at,
created_by=row.created_by,
updated_by=row.updated_by,
)
for row in rows
]
paged = PagedDataSynthesisFileTaskResponse(
content=file_items,
totalElements=total,
totalPages=(total + page_size - 1) // page_size,
page=page,
size=page_size,
)
return StandardResponse(
code=200,
message="Success",
data=paged,
)
@router.get("/file/{file_id}/chunks", response_model=StandardResponse[PagedDataSynthesisChunkResponse])
async def list_chunks_by_file(
file_id: str,
page: int = 1,
page_size: int = 10,
db: AsyncSession = Depends(get_db),
):
"""根据文件任务 ID 分页查询 chunk 记录"""
# 校验文件任务是否存在
file_task = await db.get(DataSynthesisFileInstance, file_id)
if not file_task:
raise HTTPException(status_code=404, detail="Synthesis file task not found")
base_query = select(DataSynthesisChunkInstance).where(
DataSynthesisChunkInstance.synthesis_file_instance_id == file_id
)
count_q = select(func.count()).select_from(base_query.subquery())
total = (await db.execute(count_q)).scalar_one()
if page < 1:
page = 1
if page_size < 1:
page_size = 10
result = await db.execute(
base_query.order_by(DataSynthesisChunkInstance.chunk_index.asc())
.offset((page - 1) * page_size)
.limit(page_size)
)
rows = result.scalars().all()
chunk_items = [
DataSynthesisChunkItem(
id=row.id,
synthesis_file_instance_id=row.synthesis_file_instance_id,
chunk_index=row.chunk_index,
chunk_content=row.chunk_content,
chunk_metadata=getattr(row, "chunk_metadata", None),
)
for row in rows
]
paged = PagedDataSynthesisChunkResponse(
content=chunk_items,
totalElements=total,
totalPages=(total + page_size - 1) // page_size,
page=page,
size=page_size,
)
return StandardResponse(
code=200,
message="Success",
data=paged,
)
@router.get("/chunk/{chunk_id}/data", response_model=StandardResponse[list[SynthesisDataItem]])
async def list_synthesis_data_by_chunk(
chunk_id: str,
db: AsyncSession = Depends(get_db),
):
"""根据 chunk ID 查询所有合成结果数据"""
# 可选:校验 chunk 是否存在
chunk = await db.get(DataSynthesisChunkInstance, chunk_id)
if not chunk:
raise HTTPException(status_code=404, detail="Chunk not found")
result = await db.execute(
select(SynthesisData).where(SynthesisData.chunk_instance_id == chunk_id)
)
rows = result.scalars().all()
items = [
SynthesisDataItem(
id=row.id,
data=row.data,
synthesis_file_instance_id=row.synthesis_file_instance_id,
chunk_instance_id=row.chunk_instance_id,
)
for row in rows
]
return StandardResponse(
code=200,
message="Success",
data=items,
)
@router.post("/task/{task_id}/export-dataset/{dataset_id}", response_model=StandardResponse[str])
async def export_synthesis_task_to_dataset(
task_id: str,
dataset_id: str,
db: AsyncSession = Depends(get_db),
):
"""将指定合成任务的全部合成数据归档到已有数据集中。
规则:
- 以原始文件为维度,每个原始文件生成一个 JSONL 文件;
- JSONL 文件名称与原始文件名称完全一致;
- 仅写入文件,不再创建数据集。
"""
exporter = SynthesisDatasetExporter(db)
generation = GenerationService(db)
try:
dataset = await exporter.export_task_to_dataset(task_id, dataset_id)
await generation.add_synthesis_to_graph(db, task_id, dataset_id)
except SynthesisExportError as e:
logger.error(
"Failed to export synthesis task %s to dataset %s: %s",
task_id,
dataset_id,
e,
)
raise HTTPException(status_code=400, detail=str(e))
return StandardResponse(
code=200,
message="success",
data=dataset.id,
)
@router.delete("/chunk/{chunk_id}", response_model=StandardResponse)
async def delete_chunk_with_data(
chunk_id: str,
db: AsyncSession = Depends(get_db),
):
"""删除单条 t_data_synthesis_chunk_instances 记录及其关联的所有 t_data_synthesis_data"""
chunk = await db.get(DataSynthesisChunkInstance, chunk_id)
if not chunk:
raise HTTPException(status_code=404, detail="Chunk not found")
# 先删除与该 chunk 关联的合成数据
await db.execute(
delete(SynthesisData).where(SynthesisData.chunk_instance_id == chunk_id)
)
# 再删除 chunk 本身
await db.execute(
delete(DataSynthesisChunkInstance).where(
DataSynthesisChunkInstance.id == chunk_id
)
)
await db.commit()
return StandardResponse(code=200, message="success", data=None)
@router.delete("/chunk/{chunk_id}/data", response_model=StandardResponse)
async def delete_synthesis_data_by_chunk(
chunk_id: str,
db: AsyncSession = Depends(get_db),
):
"""仅删除指定 chunk 下的全部 t_data_synthesis_data 记录,返回删除条数"""
chunk = await db.get(DataSynthesisChunkInstance, chunk_id)
if not chunk:
raise HTTPException(status_code=404, detail="Chunk not found")
result = await db.execute(
delete(SynthesisData).where(SynthesisData.chunk_instance_id == chunk_id)
)
deleted = int(getattr(result, "rowcount", 0) or 0)
await db.commit()
return StandardResponse(code=200, message="success", data=deleted)
@router.delete("/data/batch", response_model=StandardResponse)
async def batch_delete_synthesis_data(
request: BatchDeleteSynthesisDataRequest,
db: AsyncSession = Depends(get_db),
):
"""批量删除 t_data_synthesis_data 记录"""
if not request.ids:
return StandardResponse(code=200, message="success", data=0)
result = await db.execute(
delete(SynthesisData).where(SynthesisData.id.in_(request.ids))
)
deleted = int(getattr(result, "rowcount", 0) or 0)
await db.commit()
return StandardResponse(code=200, message="success", data=deleted)
@router.patch("/data/{data_id}", response_model=StandardResponse)
async def update_synthesis_data_field(
data_id: str,
body: SynthesisDataUpdateRequest,
db: AsyncSession = Depends(get_db),
):
"""修改单条 t_data_synthesis_data.data 的完整 JSON
前端传入完整 JSON,后端直接覆盖原有 data 字段,不做局部 merge。
"""
record = await db.get(SynthesisData, data_id)
if not record:
raise HTTPException(status_code=404, detail="Synthesis data not found")
# 直接整体覆盖 data 字段
record.data = body.data
await db.commit()
await db.refresh(record)
return StandardResponse(
code=200,
message="success",
data=SynthesisDataItem(
id=record.id,
data=record.data,
synthesis_file_instance_id=record.synthesis_file_instance_id,
chunk_instance_id=record.chunk_instance_id,
),
)