Spaces:
Runtime error
Runtime error
Download main.py from Chaos0818/LLMDataGenerator: direct link, hf CLI and curl.
- Browser
- Download file 16.6 kB
-
https://huggingface.co/spaces/Chaos0818/LLMDataGenerator/resolve/main/main.py
- Command line
-
hf download hf://spaces/Chaos0818/LLMDataGenerator/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Chaos0818/LLMDataGenerator/resolve/main/main.py
16.6 kB
| from storage.ali_drive import AligoUploader | |
| from llms.kimi import KimiAgent | |
| from ocr.doc2x import PDFProcessor | |
| import os | |
| import gradio as gr | |
| from datetime import datetime | |
| import shutil | |
| import time | |
| from utils import * | |
| import yaml | |
| import logging | |
| from threading import Thread | |
| from status import * | |
| # 全局状态变量 | |
| current_status = ProcessStatus.IDLE | |
| status_detail = "" | |
| # todo 性能优化 并发? | |
| # 创建全局日志捕获器 | |
| realtime_log_capture = RealTimeLogCapture(__name__) | |
| def update_status(status: ProcessStatus, detail: str = ""): | |
| """更新全局状态""" | |
| global current_status, status_detail | |
| current_status = status | |
| status_detail = detail | |
| def get_current_status_display(): | |
| """获取当前状态的显示格式""" | |
| return format_status_display(current_status, status_detail) | |
| def update_ocr_interface(file_type): | |
| if file_type == "JSON": | |
| return ( | |
| gr.update(interactive=False, value="不需要OCR"), | |
| "JSON格式不需要OCR识别,禁用OCR接口!!!", | |
| ) | |
| return gr.update(interactive=True, value="doc2x"), "PDF格式需要OCR识别" | |
| def llm_extract_question(file_path, llm): | |
| """提取问题的函数,添加日志记录""" | |
| realtime_logger = logging.getLogger(__name__) | |
| realtime_logger.info(f"开始提取问题: {file_path}") | |
| llm.get_file_info(file_path) | |
| # 获取有多少个题目以及题目编号 | |
| realtime_logger.info("获取题目信息...") | |
| question_info = llm.get_question_info() | |
| if question_info["questions"] is not None and len(question_info["questions"]) > 0: | |
| realtime_logger.info(f"找到 {len(question_info['questions'])} 个题目") | |
| # 题目分成四个一组 | |
| question_groups = [ | |
| question_info["questions"][i : i + 4] | |
| for i in range(0, len(question_info["questions"]), 4) | |
| ] | |
| realtime_logger.info(f"题目分组完成,共 {len(question_groups)} 组") | |
| jsonl_data = [] | |
| for idx, que in enumerate(question_groups, 1): | |
| update_status( | |
| ProcessStatus.EXTRACTING_QUESTIONS, | |
| f"处理第 {idx}/{len(question_groups)} 组题目", | |
| ) | |
| realtime_logger.info(f"处理第 {idx}/{len(question_groups)} 组题目...") | |
| # 处理每个部分题目 | |
| ex_q = llm.extract_question_jsonl(str(que)) | |
| try: | |
| if ex_q and isinstance(ex_q, dict) and "qlist" in ex_q: | |
| for q in ex_q["qlist"]: | |
| jsonl_data.append(q) | |
| realtime_logger.info( | |
| f"第 {idx} 组处理完成,提取到 {len(ex_q['qlist'])} 个题目" | |
| ) | |
| else: | |
| realtime_logger.warning(f"第 {idx} 组格式无效: {ex_q}") | |
| continue | |
| except Exception as e: | |
| realtime_logger.error(f"处理第 {idx} 组时出错: {e}") | |
| continue | |
| realtime_logger.info(f"题目提取完成,总共提取到 {len(jsonl_data)} 个题目") | |
| return jsonl_data | |
| else: | |
| realtime_logger.warning("未找到题目信息") | |
| return [] | |
| def process_files_core(json_files, pdf_files, file_type, ocr_choice, llm_choice): | |
| """核心处理函数,会被放在单独线程中执行""" | |
| global models | |
| realtime_logger = logging.getLogger(__name__) | |
| try: | |
| update_status(ProcessStatus.INITIALIZING, "创建临时目录") | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| temp_dir = os.path.join("temp_files", timestamp) | |
| out_dir = os.path.join(temp_dir, "out") | |
| # 中间流程 | |
| os.makedirs(temp_dir, exist_ok=True) | |
| # 交付目录 | |
| os.makedirs(out_dir, exist_ok=True) | |
| realtime_logger.info(f"开始新的处理...") | |
| realtime_logger.info(f"时间戳目录: {temp_dir}") | |
| if file_type == "JSON" and json_files is not None: | |
| update_status( | |
| ProcessStatus.COPYING_FILES, f"处理 {len(json_files)} 个JSON文件" | |
| ) | |
| realtime_logger.info(f"处理 {len(json_files)} 个JSON文件") | |
| for idx, json_file in enumerate(json_files, 1): | |
| update_status( | |
| ProcessStatus.COPYING_FILES, f"复制JSON文件 {idx}/{len(json_files)}" | |
| ) | |
| dest_path = os.path.join(temp_dir, os.path.basename(json_file.name)) | |
| shutil.copy2(json_file.name, dest_path) | |
| realtime_logger.info( | |
| f"[{idx}/{len(json_files)}] 处理JSON文件: {os.path.basename(json_file.name)}" | |
| ) | |
| elif file_type == "PDF" and pdf_files is not None: | |
| update_status( | |
| ProcessStatus.COPYING_FILES, f"处理 {len(pdf_files)} 个PDF文件" | |
| ) | |
| realtime_logger.info(f"处理 {len(pdf_files)} 个PDF文件") | |
| processed_files = [] | |
| for idx, pdf_file in enumerate(pdf_files, 1): | |
| update_status( | |
| ProcessStatus.COPYING_FILES, f"复制PDF文件 {idx}/{len(pdf_files)}" | |
| ) | |
| dest_path = os.path.join(temp_dir, os.path.basename(pdf_file.name)) | |
| shutil.copy2(pdf_file.name, dest_path) | |
| processed_files.append(dest_path) | |
| realtime_logger.info( | |
| f"[{idx}/{len(pdf_files)}] 复制PDF文件: {os.path.basename(pdf_file.name)}" | |
| ) | |
| if processed_files: | |
| update_status(ProcessStatus.OCR_PROCESSING, f"使用接口: {ocr_choice}") | |
| realtime_logger.info(f"开始OCR处理,使用接口: {ocr_choice}") | |
| models["ocr"][ocr_choice].process_pdf_files( | |
| pdf_files=processed_files, output_path=temp_dir | |
| ) | |
| realtime_logger.info("OCR处理完成") | |
| update_status(ProcessStatus.LLM_PROCESSING, f"使用模型: {llm_choice}") | |
| realtime_logger.info(f"开始LLM处理,使用模型: {llm_choice}") | |
| if file_type == "JSON" and json_files is not None: | |
| for idx, json_file in enumerate(json_files, 1): | |
| filename, file_ext = os.path.splitext(os.path.basename(json_file.name)) | |
| update_status( | |
| ProcessStatus.LLM_PROCESSING, | |
| f"处理JSON {idx}/{len(json_files)}: {filename}", | |
| ) | |
| realtime_logger.info( | |
| f"[{idx}/{len(json_files)}] 开始LLM处理: {filename}" | |
| ) | |
| # 这里可以添加JSON处理逻辑 | |
| # js_jsonl = llm_extract_question(json_file, models["llm"][llm_choice]) | |
| realtime_logger.info( | |
| f"[{idx}/{len(json_files)}] JSON处理完成: {filename}" | |
| ) | |
| elif file_type == "PDF" and pdf_files is not None: | |
| for idx, pdf_file in enumerate(pdf_files, 1): | |
| filename, file_ext = os.path.splitext(os.path.basename(pdf_file.name)) | |
| update_status( | |
| ProcessStatus.LLM_PROCESSING, | |
| f"处理PDF {idx}/{len(pdf_files)}: {filename}", | |
| ) | |
| realtime_logger.info( | |
| f"[{idx}/{len(pdf_files)}] 开始LLM处理: {filename}" | |
| ) | |
| md_path = os.path.join(temp_dir, filename, f"{filename}.md") | |
| os.makedirs(os.path.join(out_dir, filename), exist_ok=True) | |
| # 解析jsonl | |
| update_status( | |
| ProcessStatus.EXTRACTING_QUESTIONS, f"提取题目: {filename}" | |
| ) | |
| realtime_logger.info(f"提取题目中: {filename}") | |
| md_jsonl = llm_extract_question(md_path, models["llm"][llm_choice]) | |
| update_status(ProcessStatus.SAVING_RESULTS, f"保存JSONL: {filename}") | |
| realtime_logger.info(f"保存JSONL文件: {filename}.jsonl") | |
| dump_jsonl( | |
| os.path.join(out_dir, filename, f"{filename}.jsonl"), md_jsonl | |
| ) | |
| # 移动img到交付目录 | |
| img_dir = os.path.join(temp_dir, filename, "images") | |
| if os.path.exists(img_dir): | |
| update_status( | |
| ProcessStatus.MOVING_FILES, f"移动图片文件: {filename}" | |
| ) | |
| dest_img_dir = os.path.join(out_dir, filename, "images") | |
| os.makedirs(dest_img_dir, exist_ok=True) | |
| img_files = os.listdir(img_dir) | |
| realtime_logger.info(f"移动 {len(img_files)} 个图片文件到输出目录") | |
| for img_idx, img in enumerate(img_files, 1): | |
| if img_idx % 10 == 0: # 每10个文件更新一次状态 | |
| update_status( | |
| ProcessStatus.MOVING_FILES, | |
| f"移动图片 {img_idx}/{len(img_files)}", | |
| ) | |
| shutil.copy2( | |
| os.path.join(img_dir, img), os.path.join(dest_img_dir, img) | |
| ) | |
| if img_idx % 10 == 0: # 每10个文件报告一次进度 | |
| realtime_logger.info( | |
| f"已移动 {img_idx}/{len(img_files)} 个图片文件" | |
| ) | |
| realtime_logger.info("图片文件移动完成") | |
| realtime_logger.info( | |
| f"[{idx}/{len(pdf_files)}] PDF处理完成: {filename}" | |
| ) | |
| # 上传到阿里云盘 | |
| ali_drive = models["storage"]["ali_drive"] | |
| update_status(ProcessStatus.UPLOADING, "开始上传至存储") | |
| # 上传文件夹 | |
| if os.path.exists(temp_dir): | |
| upload_flag = ali_drive.upload_data(temp_dir) | |
| else: | |
| realtime_logger.info(f"路径 {temp_dir} 不存在") | |
| # 判断上传完成后删除缓存文件 | |
| if upload_flag: | |
| update_status(ProcessStatus.IDLE, "上传完成,清理临时文件") | |
| realtime_logger.info("上传完成,清理临时文件") | |
| # 删除临时目录 | |
| shutil.rmtree(temp_dir, ignore_errors=True) | |
| realtime_logger.info(f"已删除临时目录: {temp_dir}") | |
| update_status(ProcessStatus.COMPLETED, "所有文件处理完成") | |
| realtime_logger.info("所有文件处理完成!") | |
| except Exception as e: | |
| update_status(ProcessStatus.ERROR, f"错误: {str(e)}") | |
| realtime_logger.error(f"处理出错: {str(e)}") | |
| raise | |
| def process_files_with_realtime_logs( | |
| json_files, pdf_files, file_type, ocr_choice, llm_choice | |
| ): | |
| """带实时日志的文件处理函数""" | |
| # 清空之前的日志 | |
| realtime_log_capture.clear_logs() | |
| # 重置状态 | |
| update_status(ProcessStatus.INITIALIZING) | |
| # 在单独线程中运行核心处理逻辑 | |
| task_thread = Thread( | |
| target=process_files_core, | |
| args=(json_files, pdf_files, file_type, ocr_choice, llm_choice), | |
| ) | |
| task_thread.start() | |
| current_logs = "" | |
| # 实时获取并yield日志和状态 | |
| while task_thread.is_alive(): | |
| # 获取当前日志内容 | |
| log_contents = realtime_log_capture.get_logs() | |
| # 如果有新日志,则更新 | |
| if log_contents != current_logs: | |
| current_logs = log_contents | |
| yield current_logs, get_current_status_display() | |
| time.sleep(0.5) # 每0.5秒检查一次新日志 | |
| # 等待线程结束并获取最终日志 | |
| task_thread.join() | |
| final_logs = realtime_log_capture.get_logs() | |
| if final_logs != current_logs: | |
| final_logs_with_completion = ( | |
| final_logs + "\n" + "=" * 50 + "\n处理完成!\n" + "=" * 50 | |
| ) | |
| yield final_logs_with_completion, get_current_status_display() | |
| else: | |
| # 添加完成标记 | |
| final_logs_with_completion = ( | |
| final_logs + "\n" + "=" * 50 + "\n处理完成!\n" + "=" * 50 | |
| ) | |
| yield final_logs_with_completion, get_current_status_display() | |
| def update_file_inputs(file_type): | |
| if file_type == "JSON": | |
| return gr.update(visible=True), gr.update(visible=False) | |
| return gr.update(visible=False), gr.update(visible=True) | |
| def reset_status(): | |
| """重置状态为待机""" | |
| update_status(ProcessStatus.IDLE) | |
| return get_current_status_display() | |
| if __name__ == "__main__": | |
| os.makedirs("temp_files", exist_ok=True) | |
| # Load config from yaml file | |
| with open("conf/base_conf.yaml", "r") as f: | |
| config = yaml.safe_load(f) | |
| # Initialize services with API keys from config | |
| doc2x = PDFProcessor(config["ocr"]["doc2x"]["API_KEY"]) | |
| kimi = KimiAgent(api_key=config["llm"]["kimi"]["API_KEY"]) | |
| # ali_drive = AligoUploader( | |
| # email=config["storage"]["ali_drive"]["email"], | |
| # password=config["storage"]["ali_drive"]["pwd"], | |
| # name=config["storage"]["ali_drive"]["name"], | |
| # host="", | |
| # port=443, | |
| # ) | |
| ali_drive = AligoUploader( | |
| email="a652171909@gmail.com", | |
| password="mrzrmxfwlefmxhik", | |
| name=config["storage"]["ali_drive"]["name"], | |
| host="smtp.gmail.com", | |
| port=465, | |
| ) | |
| # Initialize global models | |
| global models | |
| models = dict(ocr=dict(doc2x=doc2x), llm=dict(kimi=kimi), storage=dict(ali_drive=ali_drive)) | |
| with gr.Blocks(title="文件处理系统") as demo: | |
| gr.Markdown("# 文件处理系统") | |
| # Top section | |
| with gr.Row(): | |
| # File selection column | |
| with gr.Column(scale=1): | |
| gr.Markdown("### 文件选择") | |
| file_type = gr.Radio( | |
| choices=["JSON", "PDF"], label="文件格式", value="JSON" | |
| ) | |
| json_files = gr.File( | |
| label="JSON文件", | |
| file_types=[".json"], | |
| visible=True, | |
| file_count="multiple", # 允许多文件上传 | |
| ) | |
| pdf_files = gr.File( | |
| label="PDF文件", | |
| file_types=[".pdf"], | |
| visible=False, | |
| file_count="multiple", # 允许多文件上传 | |
| ) | |
| # OCR column | |
| with gr.Column(scale=1): | |
| gr.Markdown("### OCR设置") | |
| ocr_choice = gr.Radio(choices=["doc2x"], label="OCR接口", value="doc2x") | |
| status_ocr = gr.Textbox(label="OCR 状态", interactive=False) | |
| # LLM column | |
| with gr.Column(scale=1): | |
| gr.Markdown("### LLM模型") | |
| llm_choice = gr.Radio(choices=["kimi"], label="LLM模型", value="kimi") | |
| # Control section | |
| with gr.Row(): | |
| status_text = gr.HTML( | |
| label="运行状态", value=get_current_status_display(), visible=True | |
| ) | |
| process_btn = gr.Button("开始处理", variant="primary", size="lg") | |
| clear_log_btn = gr.Button("清空日志", variant="secondary") | |
| # reset_btn = gr.Button("重置状态", variant="secondary") | |
| # Log output section - 放在最下面,占据更多空间 | |
| gr.Markdown("### 处理日志") | |
| log_output = gr.Textbox( | |
| label="", | |
| lines=20, | |
| max_lines=30, | |
| show_copy_button=True, | |
| container=True, | |
| interactive=False, | |
| placeholder="点击'开始处理'按钮查看实时日志...", | |
| ) | |
| # Event handlers | |
| file_type.change( | |
| fn=update_ocr_interface, | |
| inputs=[file_type], | |
| outputs=[ocr_choice, status_ocr], | |
| ) | |
| file_type.change( | |
| fn=update_file_inputs, inputs=[file_type], outputs=[json_files, pdf_files] | |
| ) | |
| process_btn.click( | |
| fn=process_files_with_realtime_logs, | |
| inputs=[ | |
| json_files, | |
| pdf_files, | |
| file_type, | |
| ocr_choice, | |
| llm_choice, | |
| ], | |
| outputs=[log_output, status_text], | |
| show_progress=True, | |
| ) | |
| clear_log_btn.click(fn=lambda: "", outputs=[log_output]) | |
| # reset_btn.click( | |
| # fn=reset_status, | |
| # outputs=[status_text] | |
| # ) | |
| demo.launch() | |