-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathmain.py
More file actions
688 lines (582 loc) · 26 KB
/
Copy pathmain.py
File metadata and controls
688 lines (582 loc) · 26 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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
main.py
Unified controller for prompt-library conversions.
支持的转换模式
==============
1. Excel → Docs : 将 Excel 工作簿转换为 Markdown 文档目录
2. Docs → Excel : 将 Markdown 文档目录还原为 Excel 工作簿
3. Docs → JSONL : 将 Markdown 文档转换为 JSONL 格式(保留完整元信息)
4. JSONL → Excel : 将 JSONL 转换为 Excel(单元格存储 JSON 对象)
5. Excel(JSONL) → JSONL : 将内部 JSONL 格式的 Excel 转换为 JSONL 目录(自动忽略"说明"工作表)
6. JSONL 目录 → Excel : 将 Excel(JSONL) 导出的工作表级 JSONL 目录重新合并为 Excel
数据格式规范
============
Excel 结构:
- 每个工作表(sheet) = 一个分类(category)
- 行(row) = 不同提示词
- 列(col) = 版本迭代
Excel(JSONL) 结构(内部 JSONL 格式):
- 每个工作表(sheet) = 一个分类(category),"说明"工作表会被忽略
- 每个单元格存储 JSON 对象: {"title": "...", "content": "..."}
Docs 结构:
- prompts/(N)_分类名/ # N = category_id
- prompts/(N)_分类名/(r,c)_标题.md # r=row, c=col
JSONL 格式 (每行一个 JSON 对象):
{
"category_id": 2, # 分类编号
"category": "元提示词", # 分类名称
"row": 1, # 原 Excel 行号
"col": 1, # 原 Excel 列号(版本号)
"title": "...", # 标题(截断80字符)
"content": "..." # 完整内容
}
JSONL → Excel 单元格格式:
{"title": "...", "content": "..."} # 只保留 title 和 content
目录约定
========
- Excel 源文件: ./prompt_excel/
- Docs 源目录: ./prompt_docs/
- JSONL 文件: ./prompt_jsonl/
- 输出:
- Excel→Docs: ./prompt_docs/prompt_docs_YYYY_MMDD_HHMMSS/
- Docs→Excel: ./prompt_excel/prompt_excel_YYYY_MMDD_HHMMSS/rebuilt.xlsx
- Docs→JSONL: ./prompt_jsonl/{docs_name}.jsonl
- JSONL→Excel: ./prompt_excel/{jsonl_name}.xlsx
- JSONL目录→Excel: ./prompt_excel/{jsonl_dir_name}.xlsx
- Excel(JSONL)→JSONL: ./prompt_jsonl/{excel_name}_{timestamp}/<sheet>.jsonl
使用示例
========
# 交互式选择
python3 main.py
# Excel → Docs
python3 main.py --select "prompt_excel/prompt.xlsx"
# Docs → Excel
python3 main.py --select "prompt_docs/prompt_docs_2025_1222"
# Docs → JSONL
python3 main.py --select "prompt_docs/prompt_docs_2025_1222" --mode docs2jsonl
# JSONL → Excel
python3 main.py --select "prompt_jsonl/prompt_docs.jsonl"
python3 main.py --select "prompt_jsonl/prompt_jsonl_2025_1222_004537" --mode jsonl2excel
# Excel(JSONL) → JSONL(自动检测或显式指定)
python3 main.py --select "prompt_excel/prompt_jsonl.xlsx"
python3 main.py --select "prompt_excel/prompt_jsonl.xlsx" --mode jsonl_excel2jsonl
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Sequence, Tuple
# Optional Rich UI imports (fallback to plain if unavailable)
try:
from rich.console import Console
from rich.layout import Layout
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich import box
from rich.prompt import IntPrompt
_RICH_AVAILABLE = True
except Exception: # pragma: no cover
_RICH_AVAILABLE = False
# Optional InquirerPy for arrow-key selection
try:
from InquirerPy import inquirer as _inq
_INQUIRER_AVAILABLE = True
except Exception: # pragma: no cover
_INQUIRER_AVAILABLE = False
@dataclass
class Candidate:
index: int
kind: str # "excel" | "docs" | "docs2jsonl" | "jsonl" | "jsonl_dir" | "jsonl_excel"
path: Path
label: str
def get_repo_root() -> Path:
return Path(__file__).resolve().parent
def list_excel_files(excel_dir: Path) -> List[Path]:
if not excel_dir.exists():
return []
return sorted([p for p in excel_dir.iterdir() if p.is_file() and p.suffix.lower() == ".xlsx"], key=lambda p: p.stat().st_mtime)
def has_prompt_files(directory: Path) -> bool:
if not directory.exists():
return False
# Detect files like "(r,c)_*.md" anywhere under the directory
for file_path in directory.rglob("*.md"):
name = file_path.name
if name.startswith("(") and ")_" in name:
return True
return False
def list_doc_sets(docs_dir: Path) -> List[Path]:
results: List[Path] = []
if not docs_dir.exists():
return results
# If the docs_dir itself looks like a set, include it
if has_prompt_files(docs_dir):
results.append(docs_dir)
# Also include any immediate children that look like a docs set
for child in sorted(docs_dir.iterdir()):
if child.is_dir() and has_prompt_files(child):
results.append(child)
return results
def run_start_convert(start_convert: Path, mode: str, project_root: Path, select_path: Optional[Path] = None, excel_dir: Optional[Path] = None, docs_dir: Optional[Path] = None) -> int:
"""Delegate to scripts/start_convert.py with appropriate flags."""
python_exe = sys.executable
cmd: List[str] = [python_exe, str(start_convert), "--mode", mode]
if select_path is not None:
# Always pass as repo-root-relative or absolute string
cmd.extend(["--select", str(select_path)])
if excel_dir is not None:
cmd.extend(["--excel-dir", str(excel_dir)])
if docs_dir is not None:
cmd.extend(["--docs-dir", str(docs_dir)])
# Execute in repo root to ensure relative defaults resolve correctly
proc = subprocess.run(cmd, cwd=str(project_root))
return proc.returncode
def run_docs_to_jsonl(docs_path: Path, project_root: Path) -> int:
"""Convert docs folder to JSONL format."""
import json
import re
prompts_dir = docs_path / "prompts"
if not prompts_dir.exists():
print(f"❌ 找不到 prompts 目录: {prompts_dir}")
return 1
output_dir = project_root / "prompt_jsonl"
output_dir.mkdir(parents=True, exist_ok=True)
output_file = output_dir / f"{docs_path.name}.jsonl"
records = []
for category_dir in sorted(prompts_dir.iterdir()):
if not category_dir.is_dir():
continue
m = re.match(r'\((\d+)\)_(.+)', category_dir.name)
cat_id, cat_name = (m.groups() if m else (0, category_dir.name))
for md_file in sorted(category_dir.glob("*.md")):
if md_file.name == "index.md":
continue
fm = re.match(r'\((\d+),(\d+)\)_(.+)\.md', md_file.name)
if not fm:
continue
row, col, title = fm.groups()
content = md_file.read_text(encoding='utf-8')
records.append({
"category_id": int(cat_id),
"category": cat_name,
"row": int(row),
"col": int(col),
"title": title[:80],
"content": content
})
with open(output_file, 'w', encoding='utf-8') as f:
for r in records:
f.write(json.dumps(r, ensure_ascii=False) + '\n')
print(f"✅ Docs→JSONL OK: {docs_path.name} → {output_file.relative_to(project_root)}")
return 0
def list_jsonl_files(jsonl_dir: Path) -> List[Path]:
if not jsonl_dir.exists():
return []
return sorted([p for p in jsonl_dir.iterdir() if p.is_file() and p.suffix.lower() == ".jsonl"], key=lambda p: p.stat().st_mtime)
def list_jsonl_dirs(jsonl_dir: Path) -> List[Path]:
"""列出由 Excel(JSONL)→JSONL 生成的工作表级 JSONL 目录。"""
if not jsonl_dir.exists():
return []
return sorted(
[
p
for p in jsonl_dir.iterdir()
if p.is_dir() and any(child.is_file() and child.suffix.lower() == ".jsonl" for child in p.iterdir())
],
key=lambda p: p.stat().st_mtime,
)
def is_jsonl_excel(excel_path: Path) -> bool:
"""检测 Excel 是否为内部 JSONL 格式(单元格存储 JSON 对象)"""
import json
try:
import pandas as pd
except ImportError:
return False
try:
xlsx = pd.ExcelFile(excel_path)
for sheet in xlsx.sheet_names[:2]: # 检查前两个工作表
if sheet == '说明':
continue
df = pd.read_excel(xlsx, sheet_name=sheet, header=None, nrows=1)
if df.empty:
continue
first_val = str(df.iloc[0, 0]).strip() if not pd.isna(df.iloc[0, 0]) else ""
# 检查列名或第一个单元格是否为 JSON
first_col = str(df.columns[0]).strip() if len(df.columns) > 0 else ""
for val in [first_col, first_val]:
if val.startswith('{') and val.endswith('}'):
try:
obj = json.loads(val)
if 'title' in obj and 'content' in obj:
return True
except:
pass
return False
except:
return False
def sanitize_filename(name: str) -> str:
"""将工作表名转换为稳定的文件名片段。"""
invalid_chars = '<>:"/\\|?*'
sanitized = "".join("_" if ch in invalid_chars else ch for ch in name).strip()
return sanitized.rstrip(". ") or "sheet"
def build_text_record(cat_id: int, cat_name: str, row: int, col: int, text: str) -> dict:
"""将纯文本单元格兜底转换为 JSONL 记录。"""
lines = [line.strip() for line in text.splitlines() if line.strip()]
title = lines[0] if lines else text.strip()
return {
"category_id": cat_id,
"category": cat_name,
"row": row,
"col": col,
"title": title[:80],
"content": text,
}
def run_jsonl_excel_to_jsonl(excel_path: Path, project_root: Path) -> int:
"""将内部 JSONL 格式的 Excel 转换为 JSONL 目录(忽略"说明"工作表)"""
import json
from datetime import datetime
try:
import pandas as pd
except ImportError:
print("❌ 需要 pandas: pip install pandas openpyxl")
return 1
xlsx = pd.ExcelFile(excel_path)
cat_id = 0
total_records = 0
written_files = []
timestamp = datetime.now().strftime("%Y_%m%d_%H%M%S")
output_dir = project_root / "prompt_jsonl" / f"{excel_path.stem}_{timestamp}"
output_dir.mkdir(parents=True, exist_ok=True)
for sheet_index, sheet in enumerate(xlsx.sheet_names, start=1):
if sheet == '说明':
continue
cat_id += 1
cat_name = sheet
df = pd.read_excel(xlsx, sheet_name=sheet, header=None)
sheet_lines = []
fallback_records = []
# 检查列名是否是 JSON 数据
for col_idx, col_name in enumerate(df.columns):
col_str = str(col_name).strip()
if col_str.startswith('{') and col_str.endswith('}'):
try:
obj = json.loads(col_str)
if 'title' in obj and 'content' in obj:
sheet_lines.append(json.dumps({
"category_id": cat_id,
"category": cat_name,
"row": 1,
"col": col_idx + 1,
"title": obj["title"][:80],
"content": obj["content"]
}, ensure_ascii=False))
except:
pass
# 处理数据行
for row_idx, row in df.iterrows():
for col_idx, val in enumerate(row):
if pd.isna(val):
continue
val_str = str(val).strip()
if not val_str:
continue
if val_str.startswith('{') and val_str.endswith('}'):
try:
obj = json.loads(val_str)
if 'title' in obj and 'content' in obj:
sheet_lines.append(json.dumps({
"category_id": cat_id,
"category": cat_name,
"row": row_idx + 1,
"col": col_idx + 1,
"title": obj["title"][:80],
"content": obj["content"]
}, ensure_ascii=False))
except:
pass
else:
# 跳过常见的顶栏广告/元数据噪声,但保留其他纯文本内容作为兜底记录。
if row_idx == 0 and col_idx == 0 and val_str.startswith("广告位"):
continue
fallback_records.append(
build_text_record(
cat_id=cat_id,
cat_name=cat_name,
row=row_idx + 1,
col=col_idx + 1,
text=val_str,
)
)
if not sheet_lines and fallback_records:
sheet_lines = [
json.dumps(record, ensure_ascii=False)
for record in fallback_records
]
total_records += len(sheet_lines)
file_stem = sanitize_filename(cat_name)
output_file = output_dir / f"{sheet_index:02d}_{file_stem}.jsonl"
with open(output_file, 'w', encoding='utf-8') as f:
if sheet_lines:
f.write('\n'.join(sheet_lines) + '\n')
written_files.append(output_file)
if not written_files:
print(f"❌ 未找到有效的 JSONL 数据: {excel_path}")
return 1
print(
f"✅ Excel(JSONL)→JSONL OK: {excel_path.name} → "
f"{output_dir.relative_to(project_root)} "
f"({len(written_files)} 个文件 / {total_records} 条记录)"
)
return 0
def read_jsonl_records(jsonl_paths: Sequence[Path]) -> List[dict]:
import json
records = []
for jsonl_path in jsonl_paths:
with open(jsonl_path, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
records.append(json.loads(line))
return records
def write_records_to_excel(records: List[dict], output_file: Path) -> int:
"""将 JSONL 记录写回 Excel,单元格中只保留 title/content JSON。"""
import json
from collections import defaultdict
try:
import pandas as pd
except ImportError:
print("❌ 需要 pandas: pip install pandas openpyxl")
return 1
if not records:
print("❌ JSONL 文件为空")
return 1
# category -> {row -> {col -> json_string}}
sheets_data: dict = defaultdict(lambda: defaultdict(dict))
cat_id_map = {}
for r in records:
cat_name = r["category"]
cat_id_map[r["category_id"]] = cat_name
# 单元格内容只保留 title 和 content
cell_data = {"title": r["title"], "content": r["content"]}
sheets_data[cat_name][r["row"]][r["col"]] = json.dumps(cell_data, ensure_ascii=False)
output_file.parent.mkdir(parents=True, exist_ok=True)
sorted_cats = sorted(cat_id_map.items(), key=lambda x: x[0])
with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
for cat_id, cat_name in sorted_cats:
row_data = sheets_data[cat_name]
if not row_data:
continue
max_row = max(row_data.keys())
max_col = max(c for cols in row_data.values() for c in cols.keys())
data = []
for row_idx in range(1, max_row + 1):
row_list = []
for col_idx in range(1, max_col + 1):
row_list.append(row_data.get(row_idx, {}).get(col_idx, ""))
data.append(row_list)
df = pd.DataFrame(data)
sheet_name = cat_name[:31]
df.to_excel(writer, sheet_name=sheet_name, index=False, header=False)
return len(sorted_cats)
def run_jsonl_to_excel(jsonl_path: Path, project_root: Path) -> int:
"""Convert one JSONL file to Excel, each cell contains the full JSON object as string."""
output_dir = project_root / "prompt_excel"
output_file = output_dir / f"{jsonl_path.stem}.xlsx"
sheet_count = write_records_to_excel(read_jsonl_records([jsonl_path]), output_file)
if sheet_count > 0:
print(f"✅ JSONL→Excel OK: {jsonl_path.name} → {output_file.relative_to(project_root)} ({sheet_count} 个工作表)")
return 0
return sheet_count
def run_jsonl_dir_to_excel(jsonl_dir: Path, project_root: Path) -> int:
"""Convert a directory of sheet-level JSONL files back to one Excel workbook."""
jsonl_paths = sorted(
[p for p in jsonl_dir.iterdir() if p.is_file() and p.suffix.lower() == ".jsonl"],
key=lambda p: p.name,
)
if not jsonl_paths:
print(f"❌ JSONL 目录中没有 .jsonl 文件: {jsonl_dir}")
return 1
output_dir = project_root / "prompt_excel"
output_file = output_dir / f"{jsonl_dir.name}.xlsx"
sheet_count = write_records_to_excel(read_jsonl_records(jsonl_paths), output_file)
if sheet_count > 0:
print(
f"✅ JSONL目录→Excel OK: {jsonl_dir.name} → "
f"{output_file.relative_to(project_root)} ({sheet_count} 个工作表 / {len(jsonl_paths)} 个 JSONL 文件)"
)
return 0
return sheet_count
def build_candidates(project_root: Path, excel_dir: Path, docs_dir: Path) -> List[Candidate]:
candidates: List[Candidate] = []
idx = 1
jsonl_dir = project_root / "prompt_jsonl"
for path in list_excel_files(excel_dir):
label = f"{path.name}"
# 检测是否为内部 JSONL 格式的 Excel
if is_jsonl_excel(path):
candidates.append(Candidate(index=idx, kind="jsonl_excel", path=path, label=label))
else:
candidates.append(Candidate(index=idx, kind="excel", path=path, label=label))
idx += 1
for path in list_doc_sets(docs_dir):
display = path.relative_to(project_root) if path.is_absolute() else path
# Docs → Excel
candidates.append(Candidate(index=idx, kind="docs", path=path, label=f"{display}"))
idx += 1
# Docs → JSONL
candidates.append(Candidate(index=idx, kind="docs2jsonl", path=path, label=f"{display}"))
idx += 1
for path in list_jsonl_files(jsonl_dir):
label = f"{path.name}"
candidates.append(Candidate(index=idx, kind="jsonl", path=path, label=label))
idx += 1
for path in list_jsonl_dirs(jsonl_dir):
label = f"{path.name}/"
candidates.append(Candidate(index=idx, kind="jsonl_dir", path=path, label=label))
idx += 1
return candidates
def select_interactively(candidates: Sequence[Candidate]) -> Optional[Candidate]:
if not candidates:
print("没有可用的 Excel 或 Docs 源。请将 .xlsx 放到 prompt_excel/ 或将文档放到 prompt_docs/ 下。")
return None
# Prefer arrow-key selection if available
if _INQUIRER_AVAILABLE:
try:
choices = [
{"name": f"[{c.kind.upper()}] {c.label}", "value": c.index}
for c in candidates
]
selection = _inq.select(
message="选择要转换的源(上下箭头,回车确认,Ctrl+C 取消):",
choices=choices,
default=choices[0]["value"],
).execute()
match = next((c for c in candidates if c.index == selection), None)
return match
except KeyboardInterrupt:
return None
if _RICH_AVAILABLE:
console = Console()
layout = Layout()
layout.split_column(
Layout(name="header", size=3),
Layout(name="list"),
Layout(name="footer", size=3),
)
header = Panel(Text("提示词库转换器", style="bold cyan"), subtitle="选择一个源开始转换", box=box.ROUNDED)
table = Table(box=box.SIMPLE_HEAVY)
table.add_column("编号", style="bold yellow", justify="right", width=4)
table.add_column("类型", style="magenta", width=16)
table.add_column("路径/名称", style="white")
kind_labels = {"excel": "Excel→Docs", "docs": "Docs→Excel", "docs2jsonl": "Docs→JSONL", "jsonl": "JSONL→Excel", "jsonl_excel": "Excel(JSONL)→JSONL", "jsonl_dir": "JSONL目录→Excel"}
for c in candidates:
table.add_row(str(c.index), kind_labels.get(c.kind, c.kind), c.label)
layout["header"].update(header)
layout["list"].update(Panel(table, title="可选源", border_style="cyan"))
layout["footer"].update(Panel(Text("输入编号并回车(0 退出)", style="bold"), box=box.ROUNDED))
console.print(layout)
while True:
try:
choice = IntPrompt.ask("编号", default=0)
except Exception:
return None
if choice == 0:
return None
match = next((c for c in candidates if c.index == choice), None)
if match is not None:
return match
console.print("[red]编号不存在,请重试[/red]")
# Plain fallback
kind_labels = {"excel": "Excel→Docs", "docs": "Docs→Excel", "docs2jsonl": "Docs→JSONL", "jsonl": "JSONL→Excel", "jsonl_excel": "Excel(JSONL)→JSONL", "jsonl_dir": "JSONL目录→Excel"}
print("请选择一个源进行转换:")
for c in candidates:
print(f" {c.index:2d}. [{kind_labels.get(c.kind, c.kind)}] {c.label}")
print(" 0. 退出")
while True:
try:
raw = input("输入编号后回车:").strip()
except EOFError:
return None
if not raw:
continue
if raw == "0":
return None
if not raw.isdigit():
print("请输入有效数字。")
continue
choice = int(raw)
match = next((c for c in candidates if c.index == choice), None)
if match is None:
print("编号不存在,请重试。")
continue
return match
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="prompt-library conversion controller")
p.add_argument("--excel-dir", type=str, default="prompt_excel", help="Excel sources directory (default: prompt_excel)")
p.add_argument("--docs-dir", type=str, default="prompt_docs", help="Docs sources directory (default: prompt_docs)")
p.add_argument("--select", type=str, default=None, help="Path to a specific .xlsx file or a docs folder")
p.add_argument("--mode", type=str, choices=["excel2docs", "docs2excel", "docs2jsonl", "jsonl2excel", "jsonl_excel2jsonl"], default=None, help="Conversion mode (auto-detect if not specified)")
p.add_argument("--non-interactive", action="store_true", help="Do not prompt; require --select or exit")
return p.parse_args()
def main() -> int:
repo_root = get_repo_root()
start_convert = repo_root / "scripts" / "start_convert.py"
if not start_convert.exists():
print("找不到 scripts/start_convert.py。")
return 1
args = parse_args()
excel_dir = (repo_root / args.excel_dir).resolve() if not Path(args.excel_dir).is_absolute() else Path(args.excel_dir).resolve()
docs_dir = (repo_root / args.docs_dir).resolve() if not Path(args.docs_dir).is_absolute() else Path(args.docs_dir).resolve()
# Non-interactive path with explicit selection
if args.non_interactive or args.select:
if not args.select:
print("--non-interactive 需要配合 --select 使用。")
return 2
selected = Path(args.select)
if not selected.is_absolute():
selected = (repo_root / selected).resolve()
if not selected.exists():
print(f"选择的路径不存在: {selected}")
return 2
if selected.is_file() and selected.suffix.lower() == ".xlsx":
# 检测是否为内部 JSONL 格式或显式指定模式
if args.mode == "jsonl_excel2jsonl" or is_jsonl_excel(selected):
return run_jsonl_excel_to_jsonl(selected, repo_root)
return run_start_convert(start_convert, mode="excel2docs", project_root=repo_root, select_path=selected, excel_dir=excel_dir)
if selected.is_file() and selected.suffix.lower() == ".jsonl":
return run_jsonl_to_excel(selected, repo_root)
if selected.is_dir():
if args.mode == "jsonl2excel" or (
selected.parent == (repo_root / "prompt_jsonl").resolve()
and any(p.is_file() and p.suffix.lower() == ".jsonl" for p in selected.iterdir())
):
return run_jsonl_dir_to_excel(selected, repo_root)
# Check mode or default to docs2excel
if args.mode == "docs2jsonl":
return run_docs_to_jsonl(selected, repo_root)
return run_start_convert(start_convert, mode="docs2excel", project_root=repo_root, select_path=selected, docs_dir=docs_dir)
print("无法识别的选择类型。")
return 2
# Interactive selection
candidates = build_candidates(repo_root, excel_dir, docs_dir)
chosen = select_interactively(candidates)
if chosen is None:
return 0
if chosen.kind == "excel":
return run_start_convert(start_convert, mode="excel2docs", project_root=repo_root, select_path=chosen.path, excel_dir=excel_dir)
elif chosen.kind == "jsonl_excel":
return run_jsonl_excel_to_jsonl(chosen.path, repo_root)
elif chosen.kind == "docs2jsonl":
return run_docs_to_jsonl(chosen.path, repo_root)
elif chosen.kind == "jsonl":
return run_jsonl_to_excel(chosen.path, repo_root)
elif chosen.kind == "jsonl_dir":
return run_jsonl_dir_to_excel(chosen.path, repo_root)
else:
return run_start_convert(start_convert, mode="docs2excel", project_root=repo_root, select_path=chosen.path, docs_dir=docs_dir)
if __name__ == "__main__":
sys.exit(main())