Update app.py
Browse files1234567891011121314151617181 unmodified line20212223242526272810 unmodified lines3940414243444512 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001012 unmodified lines104105106107108109110111112113114115116117import gradio as grimport pandas as pdfrom PIL import Imagefrom transformers import Qwen2VLForConditionalGeneration, AutoProcessorfrom qwen_vl_utils import process_vision_infoimport torchimport io# 1. 加载轻量版 Qwen2-VL 模型 (适合免费 CPU/GPU 节点)MODEL_NAME = "Qwen/Qwen2-VL-2B-Instruct"print("正在加载模型...")model = Qwen2VLForConditionalGeneration.from_pretrained(MODEL_NAME,torch_dtype=torch.float32, # CPU 上使用 float32 保证稳定device_map="cpu")processor = AutoProcessor.from_pretrained(MODEL_NAME)1 unmodified linedef extract_table(image: Image.Image):if image is None:return "", None, "请先上传照片!"# 提示词明确要求:必须使用标准的 Markdown 表格格式prompt = ("请识别这张照片中的所有表格和单据内容。""必须直接以 Markdown 表格的形式输出(使用 '|' 分隔列)。"10 unmodified lines}]# 模型推理text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)image_inputs, video_inputs = process_vision_info(messages)inputs = processor(12 unmodified linesgenerated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0].strip()# 安全地将文本解析为 DataFramerows = []for line in raw_text.split("\n"):line = line.strip()# 只要包含 | 的行都提取出来if "|" in line:parts = [p.strip() for p in line.split("|")]# 过滤掉开头结尾空切割if len(parts) >= 2:# 排除 Markdown 的分隔行例如 |---|---|if not all(set(p) <= set("-: ") for p in parts if p):rows.append(parts[1:-1] if len(parts) > 2 else parts)excel_path = "extracted_table.xlsx"if rows:# 第一行为表头,其余为数据header = rows[0]data = rows[1:] if len(rows) > 1 else []# 对齐列数max_len = max(len(r) for r in (data + [header]))header += [""] * (max_len - len(header))padded_data = [r + [""] * (max_len - len(r)) for r in data]df = pd.DataFrame(padded_data, columns=header)df.to_excel(excel_path, index=False)return raw_text, excel_path, f"成功提取 {len(padded_data)} 行数据!"else:# 万一依然没匹配到表格,将全部文本写入 Excel 避免输出空白df = pd.DataFrame({"识别文本": raw_text.split("\n")})df.to_excel(excel_path, index=False)return raw_text, excel_path, "未检测到标准表格格式,已将文本存入单列 Excel。"# 构建界面with gr.Blocks(title="图片转表格") as demo:gr.Markdown("## 📷 图片转电子表格")with gr.Row():with gr.Column():2 unmodified lineswith gr.Column():status_output = gr.Textbox(label="运行状态", interactive=False)text_output = gr.Markdown(label="识别出的 Markdown 内容")file_output = gr.File(label="下载 Excel 文件")submit_btn.click(fn=extract_table,inputs=[image_input],outputs=[text_output, file_output, status_output])if __name__ == "__main__":demo.launch()12345678910111213141516171819201 unmodified line222324252627282910 unmodified lines40414243444512 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495962 unmodified lines99100101102103104105106107108109110111112113114import osimport reimport ioimport pandas as pdfrom PIL import Imageimport torchimport gradio as grfrom transformers import Qwen2VLForConditionalGeneration, AutoProcessorfrom qwen_vl_utils import process_vision_infoMODEL_NAME = "Qwen/Qwen2-VL-2B-Instruct"print("正在加载模型...")model = Qwen2VLForConditionalGeneration.from_pretrained(MODEL_NAME,torch_dtype=torch.float32,device_map="cpu")processor = AutoProcessor.from_pretrained(MODEL_NAME)1 unmodified linedef extract_table(image: Image.Image):if image is None:return None, None, "请先上传照片!"prompt = ("请识别这张照片中的所有表格和单据内容。""必须直接以 Markdown 表格的形式输出(使用 '|' 分隔列)。"10 unmodified lines}]text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)image_inputs, video_inputs = process_vision_info(messages)inputs = processor(12 unmodified linesgenerated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0].strip()# 安全解析 Markdown 表格rows = []for line in raw_text.split("\n"):line = line.strip()if "|" in line:parts = [p.strip() for p in line.split("|")]if len(parts) >= 2:# 过滤分隔线if not all(set(p) <= set("-: ") for p in parts if p):rows.append(parts[1:-1] if len(parts) > 2 else parts)excel_path = os.path.abspath("extracted_table.xlsx")if rows:header = rows[0]data = rows[1:] if len(rows) > 1 else []max_len = max(len(r) for r in ([header] + data))# 自动补齐列表格列header += [f"Un-named_{i}" for i in range(len(header), max_len)]padded_data = [r + [""] * (max_len - len(r)) for r in data]df = pd.DataFrame(padded_data, columns=header)df.to_excel(excel_path, index=False)return df, excel_path, f"成功识别并提取了 {len(padded_data)} 行数据!"else:df = pd.DataFrame({"识别内容": raw_text.split("\n")})df.to_excel(excel_path, index=False)return df, excel_path, "未检测到标准表格,已导出文字清单。"# 构建 Gradio 6.x 界面with gr.Blocks(title="照片转 Excel") as demo:gr.Markdown("# 📷 照片转电子表格")with gr.Row():with gr.Column():2 unmodified lineswith gr.Column():status_output = gr.Textbox(label="运行状态", interactive=False)table_output = gr.Dataframe(label="预览表格数据", interactive=False)file_output = gr.File(label="下载 Excel 文件")# Gradio 6.x 下移除自定义 api_name,避免路由冲突submit_btn.click(fn=extract_table,inputs=[image_input],outputs=[table_output, file_output, status_output])if __name__ == "__main__":# Gradio 6.x 标准启动,不再添加 ssr_mode 参数demo.launch(show_error=True)
app.py+25-28