Desung commited on
Commit
26e1782
·
verified ·
1 Parent(s): 2917594

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +595 -4
app.py CHANGED
@@ -1,11 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
 
 
 
3
 
4
- def greet(name):
5
- return "Hello " + name + "!"
 
 
 
 
 
 
 
6
 
 
 
 
 
 
 
 
7
 
8
- demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  if __name__ == "__main__":
11
- demo.launch()
 
1
+ # Copyright 2025 lishiyan
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import shutil
17
+ import base64
18
+ import re
19
+ import json
20
+ import pytesseract
21
+ import openpyxl
22
+ import fitz # PyMuPDF
23
+ from zhipuai import ZhipuAI
24
+ from PIL import Image
25
+ from mimetypes import guess_type
26
+ from openpyxl.styles import numbers
27
+ from datetime import datetime
28
  import gradio as gr
29
+ import tempfile
30
+ from pathlib import Path
31
+ import asyncio
32
+ from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
33
+ import functools
34
+ import traceback
35
+
36
+ # ====================== Module 1: PDF/Image to Markdown ======================
37
+ class PDFImageToMarkdown:
38
+ def __init__(self, zhipu_client):
39
+ self.client = zhipu_client
40
+
41
+ def detect_text_direction(self, image):
42
+ """使用 OCR 检测图片中文本的方向。"""
43
+ ocr_result = pytesseract.image_to_osd(image)
44
+ rotation_match = re.search(r'Rotate:\s+(\d+)', ocr_result)
45
+ if rotation_match:
46
+ return int(rotation_match.group(1))
47
+ return 0
48
+
49
+ def correct_image_orientation(self, image_path):
50
+ """读取图片,根据 OCR 检测的方向信息摆正图片,并保存到指定路径。"""
51
+ image = Image.open(image_path)
52
+ rotation = self.detect_text_direction(image)
53
+ if rotation != 0:
54
+ while rotation != 0:
55
+ image = image.rotate(rotation, expand=True)
56
+ rotation = self.detect_text_direction(image)
57
+ image.save(image_path)
58
+ print(f"{image_path}: image corrected to the right direction")
59
+
60
+ def extract_imginfo_from_zhipu(self, file_path):
61
+ """通过模型获取图片信息"""
62
+ with open(file_path, 'rb') as img_file:
63
+ file_base = base64.b64encode(img_file.read()).decode('utf-8')
64
+
65
+ prompt_txt = "Precisely identify the content within an image, specifically extracting all information and table content from an invoice. Convert the extracted information into Markdown format, and ensure the output is in Chinese."
66
+
67
+ response = self.client.chat.completions.create(
68
+ model="glm-4v-plus-0111",
69
+ temperature=0,
70
+ messages=[
71
+ {
72
+ "role": "user",
73
+ "content": [
74
+ {
75
+ "type": "image_url",
76
+ "image_url": {
77
+ "url": f"data:image/png;base64,{file_base}"
78
+ }
79
+ },
80
+ {
81
+ "type": "text",
82
+ "text": prompt_txt
83
+ }
84
+ ]
85
+ }
86
+ ]
87
+ )
88
+ return response.choices[0].message.content
89
+
90
+ def remove_empty_lines(self, input_file):
91
+ """删除 markdown 中的空行和 markdown 标记"""
92
+ temp_file = input_file + '.tmp'
93
+ with open(input_file, 'r', encoding='utf-8') as infile, open(temp_file, 'w', encoding='utf-8') as outfile:
94
+ for line in infile:
95
+ clean_line = line.replace('```markdown', '').replace('```', '')
96
+ if clean_line.strip():
97
+ outfile.write(clean_line)
98
+ os.replace(temp_file, input_file)
99
+
100
+ def detect_file_type(self, file_path):
101
+ """检测文件类型,返回主要类型和子类型"""
102
+ mime_type, _ = guess_type(file_path)
103
+ if mime_type:
104
+ return mime_type.split('/')
105
+ ext = os.path.splitext(file_path)[1].lower()
106
+ if ext in ['.pdf']:
107
+ return ('application', 'pdf')
108
+ elif ext in ['.jpg', '.jpeg']:
109
+ return ('image', 'jpeg')
110
+ elif ext in ['.png']:
111
+ return ('image', 'png')
112
+ else:
113
+ raise ValueError(f"Unsupported file format: {file_path}")
114
+
115
+ def process_image_file(self, image_path):
116
+ """处理单个图片文件,校正方向并提取信息"""
117
+ self.correct_image_orientation(image_path)
118
+ return self.extract_imginfo_from_zhipu(image_path)
119
+
120
+ def pdf_to_md(self, pdf_path, image_folder, finish_folder, dpi=300):
121
+ """处理PDF文件,转换为Markdown文本"""
122
+ pdf_document = fitz.open(pdf_path)
123
+ pdf_name = os.path.splitext(os.path.basename(pdf_path))[0]
124
+ all_text = ""
125
+
126
+ for page_num in range(len(pdf_document)):
127
+ page = pdf_document.load_page(page_num)
128
+ zoom = dpi / 72.0
129
+ mat = fitz.Matrix(zoom, zoom)
130
+ pix = page.get_pixmap(matrix=mat)
131
+ image_filename = f"{pdf_name}_page_{page_num + 1}.png"
132
+ image_path = os.path.join(image_folder, image_filename)
133
+ pix.save(image_path)
134
+ image_text = self.process_image_file(image_path)
135
+ all_text += image_text + '\n'
136
+ shutil.move(image_path, os.path.join(finish_folder, image_filename))
137
+
138
+ return all_text
139
+
140
+ def file_to_md(self, input_path, image_folder, md_folder, finish_folder, dpi=300):
141
+ """主处理函数,支持多种输入文件格式"""
142
+ file_type, file_subtype = self.detect_file_type(input_path)
143
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
144
+ markdown_file_path = os.path.join(md_folder, f"{base_name}.md")
145
+
146
+ if file_type == 'application' and file_subtype == 'pdf':
147
+ all_text = self.pdf_to_md(input_path, image_folder, finish_folder, dpi)
148
+ elif file_type == 'image':
149
+ all_text = self.process_image_file(input_path)
150
+ else:
151
+ raise ValueError(f"Unsupported file type: {file_type}/{file_subtype}")
152
+
153
+ with open(markdown_file_path, 'w', encoding='utf-8') as f:
154
+ f.write(all_text)
155
+ self.remove_empty_lines(markdown_file_path)
156
+ print(f"File {input_path} converted to markdown successfully.")
157
+ return markdown_file_path
158
+
159
+ # ====================== Module 2: Markdown to JSON ======================
160
+ class MarkdownToJSON:
161
+ DEFAULT_PROMPT = """
162
+ 请将以下 Markdown 格式的发票内容转换为 JSON 格式。要求如下:
163
+
164
+ 1. **提取以下字段**:
165
+ - 发票代码(invoice_code)
166
+ - 开票日期(invoice_date)
167
+ - 购买方信息(buyer):包含名称(name)和统一社会信用代码/纳税人识别号(tax_id)
168
+ - 销售方信息(seller):包含名称(name)和统一社会信用代码/纳税人识别号(tax_id)
169
+ - 发票项目(items):每个项目包含以下字段:
170
+ - 项目名称(item_name)
171
+ - 规格型号(specification)
172
+ - 单位(unit)
173
+ - 数量(quantity)
174
+ - 单价(unit_price)
175
+ - 金额(amount)
176
+ - 税率/征收率(tax_rate)
177
+ - 税额(tax_amount)
178
+ - 合计金额(total_amount)
179
+ - 合计税额(total_tax)
180
+ - 价税合计(total_including_tax):包含大写金额(capitalized)和小写金额(numeric)
181
+ - 备注(remarks):以列表形式存储
182
+ - 开票人(issuer)
183
+
184
+ 2. **JSON 格式要求**:
185
+ - 字段名称必须与上述要求一致。
186
+ - 金额和税额字段的值应为字符串类型。
187
+ - 发票项目(items)应为数组,每个项目为一个对象。
188
+ - 备注(remarks)应为数组,每个备注为字符串。
189
+ """
190
+
191
+ def __init__(self, zhipu_client):
192
+ self.client = zhipu_client
193
+
194
+ def extract_mdinfo_from_zhipu(self, content_md, prompt_txt=None):
195
+ """调用智谱AI API,将 Markdown 内容转换为 JSON 格式"""
196
+ if prompt_txt is None:
197
+ prompt_txt = self.DEFAULT_PROMPT
198
+
199
+ messages_to_zhipu = [
200
+ {"role": "system", "content": prompt_txt},
201
+ {"role": "user", "content": content_md}
202
+ ]
203
+
204
+ try:
205
+ response = self.client.chat.completions.create(
206
+ model="glm-4-plus",
207
+ temperature=0,
208
+ top_p=0.1,
209
+ max_tokens=4095,
210
+ messages=messages_to_zhipu,
211
+ )
212
+
213
+ content_from_glm = response.choices[0].message.content
214
+ print(f"API返回原始内容:\n{content_from_glm}") # 调试输出
215
+
216
+ # 更健壮的JSON提取方式
217
+ json_str = content_from_glm.strip()
218
+ if '```json' in json_str:
219
+ json_str = json_str.split('```json')[1].split('```')[0].strip()
220
+ elif '```' in json_str:
221
+ json_str = json_str.split('```')[1].strip()
222
+
223
+ # 尝试解析JSON
224
+ try:
225
+ json_data = json.loads(json_str)
226
+ return json_data
227
+ except json.JSONDecodeError as e:
228
+ print(f"JSON解析错误,尝试修复格式: {e}")
229
+ # 尝试修复常见的JSON格式问题
230
+ json_str = re.sub(r',\s*}', '}', json_str) # 修复多余的逗号
231
+ json_str = re.sub(r',\s*]', ']', json_str)
232
+ json_str = re.sub(r'([{,]\s*)(\w+)(\s*:)', r'\1"\2"\3', json_str) # 添加缺失的引号
233
+ return json.loads(json_str)
234
+
235
+ except Exception as e:
236
+ print(f"Error during API call or JSON parsing: {e}")
237
+ print(f"Problematic content:\n{content_from_glm}")
238
+ raise ValueError(f"无法解析API返回的JSON数据: {str(e)}")
239
+
240
+ def clean_numeric_string(self, value: str) -> str:
241
+ """清理含货币符号、千位分隔符和空格的字符串"""
242
+ return value.replace('¥', '').replace(',', '').strip()
243
+
244
+ def remove_symbols(self, data):
245
+ """将空字符串、空格、无效值强制转换为 0.0"""
246
+ if 'items' in data:
247
+ for item in data['items']:
248
+ for key in ['unit_price', 'amount', 'tax_amount']:
249
+ if key in item and isinstance(item[key], str):
250
+ cleaned_value = self.clean_numeric_string(item[key])
251
+ if cleaned_value and cleaned_value.replace('.', '', 1).isdigit():
252
+ item[key] = float(cleaned_value)
253
+ else:
254
+ item[key] = 0.0
255
+
256
+ for key in ['total_amount', 'total_tax']:
257
+ if key in data and isinstance(data[key], str):
258
+ cleaned_value = self.clean_numeric_string(data[key])
259
+ if cleaned_value and cleaned_value.replace('.', '', 1).isdigit():
260
+ data[key] = float(cleaned_value)
261
+ else:
262
+ data[key] = 0.0
263
+
264
+ if 'total_including_tax' in data and isinstance(data['total_including_tax'], dict):
265
+ numeric_value = data['total_including_tax'].get('numeric')
266
+ if isinstance(numeric_value, str):
267
+ cleaned_value = self.clean_numeric_string(numeric_value)
268
+ if cleaned_value and cleaned_value.replace('.', '', 1).isdigit():
269
+ data['total_including_tax']['numeric'] = float(cleaned_value)
270
+ else:
271
+ data['total_including_tax']['numeric'] = 0.0
272
+
273
+ return data
274
+
275
+ def md_to_json(self, md_dir, json_dir, finish_folder, prompt_text=None):
276
+ """将指定目录下的 Markdown 文件转换为 JSON 文件"""
277
+ for filename in os.listdir(md_dir):
278
+ if filename.endswith(".md"):
279
+ filepath = os.path.join(md_dir, filename)
280
+ try:
281
+ with open(filepath, 'r', encoding='utf-8') as file:
282
+ markdown_content = file.read()
283
+
284
+ # 增加调试输出
285
+ print(f"处理文件: {filename}")
286
+ print(f"Markdown内容预览:\n{markdown_content[:500]}...")
287
+
288
+ extracted_info = self.extract_mdinfo_from_zhipu(markdown_content, prompt_text)
289
+ extracted_info = self.remove_symbols(extracted_info)
290
+
291
+ json_filename = os.path.splitext(filename)[0] + ".json"
292
+ json_filepath = os.path.join(json_dir, json_filename)
293
+
294
+ with open(json_filepath, 'w', encoding='utf-8') as json_file:
295
+ json.dump(extracted_info, json_file, indent=4, ensure_ascii=False)
296
+
297
+ print(f"JSON文件保存成功: {json_filepath}")
298
+ shutil.move(filepath, os.path.join(finish_folder, filename))
299
+
300
+ except Exception as e:
301
+ print(f"处理文件 {filename} 失败: {str(e)}")
302
+ # 将失败文件移动到特定目录以便检查
303
+ error_folder = os.path.join(os.path.dirname(finish_folder), "errors")
304
+ os.makedirs(error_folder, exist_ok=True)
305
+ shutil.move(filepath, os.path.join(error_folder, filename))
306
+ continue
307
+
308
+ # ====================== Module 3: JSON to Excel ======================
309
+ class JSONToExcel:
310
+ def json_to_exl(self, json_folder, output_folder):
311
+ """从指定文件夹中读取 JSON 文件,并将所有相关信息填入新建的 Excel 表格中"""
312
+ workbook = openpyxl.Workbook()
313
+ sheet = workbook.active
314
+ sheet.title = "发票信息"
315
+
316
+ headers = [
317
+ "发票代码", "开票日期", "项目名称", "规格型号", "单位", "数量", "单价",
318
+ "金额", "税率", "税额", "金额+税额", "卖方名称", "卖方税号", "买方名称",
319
+ "买方税号", "发票总额", "总税额", "价税合计(大写)", "价税合计(数值)",
320
+ "备注", "开票人", "来源文件"
321
+ ]
322
+
323
+ for col, header in enumerate(headers, start=1):
324
+ sheet.cell(row=1, column=col, value=header)
325
+
326
+ for filename in os.listdir(json_folder):
327
+ if filename.endswith(".json"):
328
+ filepath = os.path.join(json_folder, filename)
329
+ with open(filepath, 'r', encoding='utf-8') as json_file:
330
+ data = json.load(json_file)
331
+
332
+ invoice_code = data.get("invoice_code", "")
333
+ invoice_date = data.get("invoice_date", "")
334
+ buyer = data.get("buyer", {})
335
+ seller = data.get("seller", {})
336
+ remarks = "\n".join(data.get("remarks", [])) if data.get("remarks") else ""
337
+ issuer = data.get("issuer", "")
338
+
339
+ items = data.get("items", [])
340
+ for item in items:
341
+ row = sheet.max_row + 1
342
+
343
+ sheet.cell(row=row, column=1, value=invoice_code)
344
+ sheet.cell(row=row, column=2, value=invoice_date)
345
+ sheet.cell(row=row, column=3, value=item.get("item_name", ""))
346
+ sheet.cell(row=row, column=4, value=item.get("specification", ""))
347
+ sheet.cell(row=row, column=5, value=item.get("unit", ""))
348
+ sheet.cell(row=row, column=6, value=item.get("quantity", ""))
349
+
350
+ sheet.cell(row=row, column=7, value=item.get("unit_price", 0))
351
+ sheet.cell(row=row, column=7).number_format = numbers.FORMAT_NUMBER_00
352
+
353
+ sheet.cell(row=row, column=8, value=item.get("amount", 0))
354
+ sheet.cell(row=row, column=8).number_format = numbers.FORMAT_NUMBER_00
355
+
356
+ sheet.cell(row=row, column=9, value=item.get("tax_rate", ""))
357
+
358
+ sheet.cell(row=row, column=10, value=item.get("tax_amount", 0))
359
+ sheet.cell(row=row, column=10).number_format = numbers.FORMAT_NUMBER_00
360
+
361
+ total_amount = item.get("amount", 0) + item.get("tax_amount", 0)
362
+ sheet.cell(row=row, column=11, value=total_amount)
363
+ sheet.cell(row=row, column=11).number_format = numbers.FORMAT_NUMBER_00
364
+
365
+ sheet.cell(row=row, column=12, value=seller.get("name", ""))
366
+ sheet.cell(row=row, column=13, value=seller.get("tax_id", ""))
367
+
368
+ sheet.cell(row=row, column=14, value=buyer.get("name", ""))
369
+ sheet.cell(row=row, column=15, value=buyer.get("tax_id", ""))
370
+
371
+ sheet.cell(row=row, column=16, value=data.get("total_amount", 0))
372
+ sheet.cell(row=row, column=16).number_format = numbers.FORMAT_NUMBER_00
373
+
374
+ sheet.cell(row=row, column=17, value=data.get("total_tax", 0))
375
+ sheet.cell(row=row, column=17).number_format = numbers.FORMAT_NUMBER_00
376
+
377
+ total_including_tax = data.get("total_including_tax", {})
378
+ sheet.cell(row=row, column=18, value=total_including_tax.get("capitalized", ""))
379
+ sheet.cell(row=row, column=19, value=total_including_tax.get("numeric", 0))
380
+ sheet.cell(row=row, column=19).number_format = numbers.FORMAT_NUMBER_00
381
+
382
+ sheet.cell(row=row, column=20, value=remarks)
383
+ sheet.cell(row=row, column=21, value=issuer)
384
+ sheet.cell(row=row, column=22, value=os.path.splitext(filename)[0])
385
+
386
+ for column in sheet.columns:
387
+ max_length = 0
388
+ column_letter = column[0].column_letter
389
+ for cell in column:
390
+ try:
391
+ if len(str(cell.value)) > max_length:
392
+ max_length = len(str(cell.value))
393
+ except:
394
+ pass
395
+ adjusted_width = (max_length + 2) * 1.2
396
+ sheet.column_dimensions[column_letter].width = adjusted_width
397
+
398
+ os.makedirs(output_folder, exist_ok=True)
399
+ # 修改时间戳格式为更易读的形式
400
+ timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
401
+ excel_filename = f"发票信息汇总_{timestamp}.xlsx"
402
+ excel_path = os.path.join(output_folder, excel_filename)
403
+
404
+ workbook.save(excel_path)
405
+ print(f"数据已成功写入新建的 Excel 文件: {excel_path}")
406
+ return excel_path
407
+
408
+
409
+ # ====================== 多线程处理函数 ======================
410
+ async def process_single_file(file_path, client, image_folder, md_folder, finish_folder):
411
+ """异步处理单个文件"""
412
+ pdf_to_md = PDFImageToMarkdown(client)
413
+ try:
414
+ # 步骤1: 文件转为Markdown
415
+ md_path = pdf_to_md.file_to_md(file_path, image_folder, md_folder, finish_folder)
416
+ return md_path
417
+ except Exception as e:
418
+ print(f"Error processing file {file_path}: {e}")
419
+ return None
420
+
421
+ async def process_md_to_json(md_path, client, json_folder, finish_folder):
422
+ """异步处理Markdown转JSON"""
423
+ md_to_json = MarkdownToJSON(client)
424
+ try:
425
+ md_to_json.md_to_json(os.path.dirname(md_path), json_folder, finish_folder)
426
+ return True
427
+ except Exception as e:
428
+ print(f"Error converting {md_path} to JSON: {e}")
429
+ return False
430
+
431
+ async def process_invoices(api_key, files, progress=gr.Progress()):
432
+ """修改后的批量处理函���,支持并发"""
433
+ # 进度条
434
+ progress(0, desc="开始处理")
435
+
436
+ if not api_key:
437
+ raise gr.Error("请输入智谱 API Key")
438
+
439
+ try:
440
+ client = ZhipuAI(api_key=api_key)
441
+ # 测试API连接
442
+ test_response = client.chat.completions.create(
443
+ model="glm-4",
444
+ messages=[{"role": "user", "content": "test"}],
445
+ temperature=0
446
+ )
447
+ print(f"API测试响应: {test_response}")
448
+ except Exception as e:
449
+ raise gr.Error(f"API Key 无效或验证失败: {str(e)}")
450
+
451
+ # 创建临时目录并检查权限
452
+ try:
453
+ temp_dir = tempfile.mkdtemp(prefix="invoice_processing_")
454
+ print(f"临时目录创建成功: {temp_dir}")
455
+
456
+ image_folder = os.path.join(temp_dir, "images")
457
+ md_folder = os.path.join(temp_dir, "markdown")
458
+ json_folder = os.path.join(temp_dir, "json")
459
+ finish_folder = os.path.join(temp_dir, "finished")
460
+
461
+ for folder in [image_folder, md_folder, json_folder, finish_folder]:
462
+ os.makedirs(folder, exist_ok=True)
463
+ print(f"创建文件夹: {folder}")
464
+
465
+ # 检查文件夹是否可写
466
+ test_file = os.path.join(folder, "test.txt")
467
+ with open(test_file, "w") as f:
468
+ f.write("test")
469
+ os.remove(test_file)
470
+ except Exception as e:
471
+ raise gr.Error(f"无法创建临时目录: {str(e)}")
472
+
473
+ try:
474
+ progress(0.05, desc="准备并发处理...")
475
+
476
+ # 初始化处理器
477
+ pdf_to_md = PDFImageToMarkdown(client)
478
+ md_to_json = MarkdownToJSON(client)
479
+ json_to_excel = JSONToExcel()
480
+
481
+ # 先同步处理一个文件测试流程
482
+ test_success = False
483
+ if files:
484
+ first_file = files[0].name
485
+ print(f"测试处理第一个文件: {first_file}")
486
+
487
+ try:
488
+ # 测试PDF/Image转Markdown
489
+ md_path = pdf_to_md.file_to_md(first_file, image_folder, md_folder, finish_folder)
490
+ print(f"成功生成Markdown: {md_path}")
491
+
492
+ # 测试Markdown转JSON
493
+ md_to_json.md_to_json(md_folder, json_folder, finish_folder)
494
+ print(f"成功生成JSON文件在: {json_folder}")
495
+
496
+ test_success = True
497
+ except Exception as e:
498
+ print(f"测试文件处理失败: {str(e)}")
499
+ traceback.print_exc()
500
+
501
+ if not test_success:
502
+ raise gr.Error("测试文件处理失败,请检查文件格式是否正确")
503
+
504
+ # 如果有多个文件,继续处理剩余文件
505
+ if len(files) > 1:
506
+ with ThreadPoolExecutor(max_workers=4) as executor:
507
+ loop = asyncio.get_event_loop()
508
+
509
+ # 第一阶段: 并行处理文件到Markdown
510
+ md_tasks = []
511
+ for i, file in enumerate(files[1:]): # 跳过已测试的第一个文件
512
+ file_path = file.name
513
+ task = loop.run_in_executor(
514
+ executor,
515
+ functools.partial(
516
+ pdf_to_md.file_to_md,
517
+ input_path=file_path,
518
+ image_folder=image_folder,
519
+ md_folder=md_folder,
520
+ finish_folder=finish_folder
521
+ )
522
+ )
523
+ md_tasks.append(task)
524
+ progress(0.1 + 0.4*(i/len(files)), desc=f"处理文件中 ({i+2}/{len(files)})")
525
+
526
+ await asyncio.gather(*md_tasks)
527
 
528
+ # 处理Markdown到JSON
529
+ progress(0.6, desc="转换JSON中...")
530
+ md_to_json.md_to_json(md_folder, json_folder, finish_folder)
531
 
532
+ # 生成Excel
533
+ progress(0.9, desc="生成Excel...")
534
+ if len(os.listdir(json_folder)) > 0:
535
+ excel_path = json_to_excel.json_to_exl(json_folder, temp_dir)
536
+ print(f"处理完成,结果保存在: {excel_path}")
537
+ progress(1.0, desc="处理完成")
538
+ return excel_path, 100
539
+ else:
540
+ raise gr.Error("没有生成有效的JSON文件")
541
 
542
+ except Exception as e:
543
+ print(f"处理过程中发生错误: {str(e)}")
544
+ traceback.print_exc()
545
+ raise gr.Error(f"处理失败: {str(e)}")
546
+ finally:
547
+ # 调试时可以先不删除临时文件
548
+ pass
549
 
550
+ # ====================== 界面配置 ======================
551
+ with gr.Blocks(title="发票识别系统") as demo:
552
+ gr.Markdown("# 发票识别系统")
553
+ gr.Markdown("上传PDF或图片格式的发票,系统将自动提取信息并生成Excel文件")
554
+
555
+ with gr.Row():
556
+ with gr.Column():
557
+ api_key = gr.Textbox(
558
+ label="输入智谱 API Key",
559
+ placeholder="请输入您的智谱 API Key",
560
+ type="password"
561
+ )
562
+
563
+ with gr.Row():
564
+ with gr.Column():
565
+ file_input = gr.File(
566
+ label="上传发票文件(可多选)",
567
+ file_types=[".pdf", ".jpg", ".jpeg", ".png"],
568
+ file_count="multiple"
569
+ )
570
+ with gr.Column():
571
+ # 将进度条和下载结果组合在一起
572
+ with gr.Group():
573
+ file_output = gr.File(label="下载Excel结果")
574
+ progress_bar = gr.Slider(
575
+ minimum=0, maximum=100, value=0,
576
+ label="处理进度",
577
+ interactive=False,
578
+ visible=False,
579
+ elem_classes=["compact-progress"] # 添加自定义样式类
580
+ )
581
+
582
+ submit_btn = gr.Button("开始处理", size="lg")
583
+
584
+ # CSS样式调整
585
+ demo.css = """
586
+ .compact-progress {
587
+ margin-top: 8px;
588
+ margin-bottom: 8px;
589
+ }
590
+ .compact-progress .wrap {
591
+ padding: 0 !important;
592
+ }
593
+ """
594
+
595
+ submit_btn.click(
596
+ fn=lambda api_key, files: asyncio.run(process_invoices(api_key, files, progress=gr.Progress())),
597
+ inputs=[api_key, file_input],
598
+ outputs=[file_output, progress_bar]
599
+ )
600
 
601
  if __name__ == "__main__":
602
+ demo.launch()