MikeMai commited on
Commit
630f048
·
verified ·
1 Parent(s): 95e666f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +545 -549
app.py CHANGED
@@ -1,549 +1,545 @@
1
- import os
2
- from dotenv import load_dotenv
3
-
4
- import json
5
- import pandas as pd
6
-
7
- import zipfile
8
- import xml.etree.ElementTree as ET
9
- from io import BytesIO
10
-
11
- from openai import OpenAI
12
-
13
- import re
14
-
15
- import logging
16
-
17
- load_dotenv()
18
- HF_API_KEY = os.getenv("HF_API_KEY")
19
-
20
- # Configure logging to write to 'zaoju_logs.log' without using pickle
21
- logging.basicConfig(
22
- filename='extract_po_logs.log',
23
- level=logging.INFO,
24
- format='%(asctime)s - %(levelname)s - %(message)s',
25
- encoding='utf-8'
26
- )
27
-
28
- # Default Word XML namespace
29
- DEFAULT_NS = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
30
- NS = None # Global variable to store the namespace
31
-
32
- def get_namespace(root):
33
- """Extracts the primary namespace from the XML root element while keeping the default."""
34
- global NS
35
-
36
- if NS is None:
37
- ns = root.tag.split('}')[0].strip('{')
38
- NS = {'w': ns} if ns else DEFAULT_NS
39
- return NS
40
-
41
- # --- Helper Functions for DOCX Processing ---
42
-
43
- def extract_text_from_cell(cell):
44
- """Extracts text from a Word table cell, preserving line breaks and reconstructing split words."""
45
- paragraphs = cell.findall('.//w:p', NS)
46
- lines = []
47
-
48
- for paragraph in paragraphs:
49
- # Get all text runs and concatenate their contents
50
- text_runs = [t.text for t in paragraph.findall('.//w:t', NS) if t.text]
51
- line = ''.join(text_runs).strip() # Merge split words properly
52
-
53
- if line: # Add only non-empty lines
54
- lines.append(line)
55
-
56
- return lines # Return list of lines to preserve line breaks
57
-
58
- def clean_spaces(text):
59
- """
60
- Removes excessive spaces between Chinese characters while preserving spaces in English words.
61
- """
62
- # Remove spaces **between** Chinese characters but keep English spaces
63
- text = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', text)
64
- return text.strip()
65
-
66
- def extract_key_value_pairs(text, target_dict=None):
67
- """
68
- Extracts multiple key-value pairs from a given text.
69
- - First, split by more than 3 spaces (`\s{3,}`) **only if the next segment contains a `:`.**
70
- - Then, process each segment by splitting at `:` to correctly assign keys and values.
71
- """
72
- if target_dict is None:
73
- target_dict = {}
74
-
75
- text = text.replace(":", ":") # Normalize Chinese colons to English colons
76
-
77
- # Step 1: Check if splitting by more than 3 spaces is necessary
78
- segments = re.split(r'(\s{3,})', text) # Use raw string to prevent invalid escape sequence
79
-
80
- # Step 2: Process each segment, ensuring we only split if the next part has a `:`
81
- merged_segments = []
82
- temp_segment = ""
83
-
84
- for segment in segments:
85
- if ":" in segment: # If segment contains `:`, it's a valid split point
86
- if temp_segment:
87
- merged_segments.append(temp_segment.strip())
88
- temp_segment = ""
89
- merged_segments.append(segment.strip())
90
- else:
91
- temp_segment += " " + segment.strip()
92
-
93
- if temp_segment:
94
- merged_segments.append(temp_segment.strip())
95
-
96
- # Step 3: Extract key-value pairs correctly
97
- for segment in merged_segments:
98
- if ':' in segment:
99
- key, value = segment.split(':', 1) # Only split at the first colon
100
- key, value = key.strip(), value.strip() # Clean spaces
101
-
102
- if key in target_dict:
103
- target_dict[key] += "\n" + value # Append if key already exists
104
- else:
105
- target_dict[key] = value
106
-
107
- return target_dict
108
-
109
- # --- Table Processing Functions ---
110
-
111
- def process_single_column_table(rows):
112
- """Processes a single-column table and returns the extracted lines as a list."""
113
- single_column_data = []
114
-
115
- for row in rows:
116
- cells = row.findall('.//w:tc', NS)
117
- if len(cells) == 1:
118
- cell_lines = extract_text_from_cell(cells[0]) # Extract all lines from the cell
119
-
120
- # Append each line directly to the list without splitting
121
- single_column_data.extend(cell_lines)
122
-
123
- return single_column_data # Return the list of extracted lines
124
-
125
- def process_buyer_seller_table(rows):
126
- """Processes a two-column buyer-seller table into a structured dictionary using the first row as keys."""
127
- headers = [extract_text_from_cell(cell) for cell in rows[0].findall('.//w:tc', NS)]
128
- if len(headers) != 2:
129
- return None # Not a buyer-seller table
130
-
131
- # determine role based on header text
132
- def get_role(header_text, default_role):
133
- header_text = header_text.lower() # Convert to lowercase
134
- if '买方' in header_text or 'buyer' in header_text or '甲方' in header_text:
135
- return 'buyer_info'
136
- elif '卖方' in header_text or 'seller' in header_text or '乙方' in header_text:
137
- return 'seller_info'
138
- else:
139
- return default_role # Default if no keyword is found
140
-
141
- # Determine the keys for buyer and seller columns
142
- buyer_key = get_role(headers[0][0], 'buyer_info')
143
- seller_key = get_role(headers[1][0], 'seller_info')
144
-
145
- # Initialize the dictionary using the determined keys
146
- buyer_seller_data = {
147
- buyer_key: {},
148
- seller_key: {}
149
- }
150
-
151
- for row in rows:
152
- cells = row.findall('.//w:tc', NS)
153
- if len(cells) == 2:
154
- buyer_lines = extract_text_from_cell(cells[0])
155
- seller_lines = extract_text_from_cell(cells[1])
156
-
157
- for line in buyer_lines:
158
- extract_key_value_pairs(line, buyer_seller_data[buyer_key])
159
-
160
- for line in seller_lines:
161
- extract_key_value_pairs(line, buyer_seller_data[seller_key])
162
-
163
- return buyer_seller_data
164
-
165
- def process_summary_table(rows):
166
- """Processes a two-column summary table where keys are extracted as dictionary keys."""
167
- extracted_data = []
168
-
169
- for row in rows:
170
- cells = row.findall('.//w:tc', NS)
171
- if len(cells) == 2:
172
- key = " ".join(extract_text_from_cell(cells[0]))
173
- value = " ".join(extract_text_from_cell(cells[1]))
174
- extracted_data.append({key: value})
175
-
176
- return extracted_data
177
-
178
- def extract_headers(first_row_cells):
179
- """Extracts unique column headers from the first row of a table."""
180
- headers = []
181
- header_count = {}
182
- for cell in first_row_cells:
183
- cell_text = " ".join(extract_text_from_cell(cell))
184
- grid_span = cell.find('.//w:gridSpan', NS)
185
- col_span = int(grid_span.attrib.get(f'{{{NS["w"]}}}val', '1')) if grid_span is not None else 1
186
- for _ in range(col_span):
187
- # Ensure header uniqueness by appending an index if repeated
188
- if cell_text in header_count:
189
- header_count[cell_text] += 1
190
- unique_header = f"{cell_text}_{header_count[cell_text]}"
191
- else:
192
- header_count[cell_text] = 1
193
- unique_header = cell_text
194
- headers.append(unique_header if unique_header else f"Column_{len(headers) + 1}")
195
- return headers
196
-
197
- def process_long_table(rows):
198
- """Processes a standard table and correctly handles horizontally merged cells."""
199
- if not rows:
200
- return [] # Avoid IndexError
201
-
202
- headers = extract_headers(rows[0].findall('.//w:tc', NS))
203
- table_data = []
204
- vertical_merge_tracker = {}
205
-
206
- for row in rows[1:]:
207
- row_data = {}
208
- cells = row.findall('.//w:tc', NS)
209
- running_index = 0
210
-
211
- for cell in cells:
212
- cell_text = " ".join(extract_text_from_cell(cell))
213
-
214
- # Consistent Namespace Handling for Horizontal Merge
215
- grid_span = cell.find('.//w:gridSpan', NS)
216
- grid_span_val = grid_span.attrib.get(f'{{{NS["w"]}}}val') if grid_span is not None else '1'
217
- col_span = int(grid_span_val)
218
-
219
- # Handle vertical merge
220
- v_merge = cell.find('.//w:vMerge', NS)
221
- if v_merge is not None:
222
- v_merge_val = v_merge.attrib.get(f'{{{NS["w"]}}}val')
223
- if v_merge_val == 'restart':
224
- vertical_merge_tracker[running_index] = cell_text
225
- else:
226
- # Repeat the value from the previous row's merged cell
227
- cell_text = vertical_merge_tracker.get(running_index, "")
228
-
229
- # Repeat the value for horizontally merged cells
230
- start_col = running_index
231
- end_col = running_index + col_span
232
-
233
- # Repeat the value for each spanned column
234
- for col in range(start_col, end_col):
235
- key = headers[col] if col < len(headers) else f"Column_{col+1}"
236
- row_data[key] = cell_text
237
-
238
- # Update the running index to the end of the merged cell
239
- running_index = end_col
240
-
241
- # Fill remaining columns with empty strings to maintain alignment
242
- while running_index < len(headers):
243
- row_data[headers[running_index]] = ""
244
- running_index += 1
245
-
246
- table_data.append(row_data)
247
-
248
- return table_data
249
-
250
- def extract_tables(root):
251
- """Extracts tables from the DOCX document and returns structured data."""
252
- tables = root.findall('.//w:tbl', NS)
253
- table_data = {}
254
- table_paragraphs = set()
255
-
256
- for table_index, table in enumerate(tables, start=1):
257
- rows = table.findall('.//w:tr', NS)
258
- if not rows:
259
- continue # Skip empty tables
260
-
261
- for paragraph in table.findall('.//w:p', NS):
262
- table_paragraphs.add(paragraph)
263
-
264
- first_row_cells = rows[0].findall('.//w:tc', NS)
265
- num_columns = len(first_row_cells)
266
-
267
- if num_columns == 1:
268
- single_column_data = process_single_column_table(rows)
269
- if single_column_data:
270
- table_data[f"table_{table_index}_single_column"] = single_column_data
271
- continue # Skip further processing for this table
272
-
273
- summary_start_index = None
274
- for i, row in enumerate(rows):
275
- if len(row.findall('.//w:tc', NS)) == 2:
276
- summary_start_index = i
277
- break
278
-
279
- long_table_data = []
280
- summary_data = []
281
-
282
- if summary_start_index is not None and summary_start_index > 0:
283
- long_table_data = process_long_table(rows[:summary_start_index])
284
- elif summary_start_index is None:
285
- long_table_data = process_long_table(rows)
286
-
287
- if summary_start_index is not None:
288
- is_buyer_seller_table = all(len(row.findall('.//w:tc', NS)) == 2 for row in rows)
289
- if is_buyer_seller_table:
290
- buyer_seller_data = process_buyer_seller_table(rows)
291
- if buyer_seller_data:
292
- table_data[f"table_{table_index}_buyer_seller"] = buyer_seller_data
293
- else:
294
- summary_data = process_summary_table(rows[summary_start_index:])
295
-
296
- if long_table_data:
297
- table_data[f"long_table_{table_index}"] = long_table_data
298
- if summary_data:
299
- table_data[f"long_table_{table_index}_summary"] = summary_data
300
-
301
- return table_data, table_paragraphs
302
-
303
- # --- Non-Table Processing Functions ---
304
-
305
- def extract_text_outside_tables(root, table_paragraphs):
306
- """Extracts text from paragraphs outside tables in the document."""
307
- extracted_text = []
308
-
309
- # print(ET.tostring(root, encoding='unicode'))
310
- for paragraph in root.findall('.//w:p', NS):
311
- if paragraph in table_paragraphs:
312
- continue # Skip paragraphs inside tables
313
-
314
- texts = [t.text.strip() for t in paragraph.findall('.//w:t', NS) if t.text]
315
- line = clean_spaces(' '.join(texts).replace(';', '').replace(';','').replace(':',':')) # Remove semicolons and clean spaces
316
-
317
- if ':' in line:
318
- extracted_text.append(line)
319
-
320
- return extracted_text
321
-
322
- # --- Main Extraction Functions ---
323
-
324
- def extract_docx_as_xml(file_bytes, save_xml=False, xml_filename="document.xml"):
325
-
326
- # Ensure file_bytes is at the start position
327
- file_bytes.seek(0)
328
-
329
- with zipfile.ZipFile(file_bytes, 'r') as docx:
330
- with docx.open('word/document.xml') as xml_file:
331
- xml_content = xml_file.read().decode('utf-8')
332
- if save_xml:
333
- with open(xml_filename, "w", encoding="utf-8") as f:
334
- f.write(xml_content)
335
- return xml_content
336
-
337
- def xml_to_json(xml_content, save_json=False, json_filename="extracted_data.json"):
338
-
339
- tree = ET.ElementTree(ET.fromstring(xml_content))
340
- root = tree.getroot()
341
-
342
- table_data, table_paragraphs = extract_tables(root)
343
- extracted_data = table_data
344
- extracted_data["non_table_data"] = extract_text_outside_tables(root, table_paragraphs)
345
-
346
- if save_json:
347
- with open(json_filename, "w", encoding="utf-8") as f:
348
- json.dump(extracted_data, f, ensure_ascii=False, indent=4)
349
-
350
- return json.dumps(extracted_data, ensure_ascii=False, indent=4)
351
-
352
- def deepseek_extract_contract_summary(json_data, save_json=False):
353
- """Sends extracted JSON data to OpenAI and returns formatted structured JSON."""
354
-
355
- # Step 1: Convert JSON string to Python dictionary
356
- contract_data = json.loads(json_data)
357
-
358
- # Step 2: Remove keys that contain "long_table"
359
- filtered_contract_data = {key: value for key, value in contract_data.items() if "long_table" not in key}
360
-
361
- # Step 3: Convert back to JSON string (if needed)
362
- json_output = json.dumps(filtered_contract_data, ensure_ascii=False, indent=4)
363
-
364
- prompt = """You are given a contract in JSON format. Extract the following information:
365
-
366
- # Response Format
367
- Return the extracted information as a structured JSON in the exact format shown below (Do not repeat any keys):
368
-
369
- {
370
- "合同编号":
371
- "采购经办人":
372
- "接收人":
373
- "Recipient":
374
- "接收地":
375
- "Place of receipt":
376
- "供应商":
377
- "币种":
378
- "合同日期":
379
- "供货日期":
380
- }
381
-
382
- Contract data in JSON format:""" + f"""
383
- {json_output}"""
384
-
385
- messages = [
386
- {
387
- "role": "user",
388
- "content": prompt
389
- }
390
- ]
391
-
392
- client = OpenAI(
393
- base_url="https://router.huggingface.co/novita",
394
- api_key=HF_API_KEY,
395
- )
396
-
397
- completion = client.chat.completions.create(
398
- model="deepseek/deepseek-r1-distill-qwen-14b",
399
- messages=messages,
400
- )
401
-
402
- contract_summary = re.sub(r"<think>.*?</think>\s*", "", completion.choices[0].message.content, flags=re.DOTALL) # Remove think
403
-
404
- contract_summary = re.sub(r"^```json\n|```$", "", contract_summary, flags=re.DOTALL) # Remove ```
405
-
406
- if save_json:
407
- with open("extracted_contract_summary.json", "w", encoding="utf-8") as f:
408
- f.write(contract_summary)
409
-
410
- return json.dumps(contract_summary, ensure_ascii=False, indent=4)
411
-
412
- def deepseek_extract_price_list(json_data):
413
- """Sends extracted JSON data to OpenAI and returns formatted structured JSON."""
414
-
415
- # Step 1: Convert JSON string to Python dictionary
416
- contract_data = json.loads(json_data)
417
-
418
- # Step 2: Remove keys that contain "long_table"
419
- filtered_contract_data = {key: value for key, value in contract_data.items() if "long_table" in key}
420
-
421
- # Step 3: Convert back to JSON string (if needed)
422
- json_output = json.dumps(filtered_contract_data, ensure_ascii=False, indent=4)
423
-
424
- print(json_output)
425
-
426
- prompt = """You are given a price list in JSON format. Extract the following information in CSV format:
427
-
428
- # Response Format
429
- Return the extracted information as a CSV in the exact format shown below:
430
-
431
- 物料名称, 物料名称(英文), 物料规格, 采购数量, 单位, 单价, 计划号
432
-
433
- JSON data:""" + f"""
434
- {json_output}"""
435
-
436
- messages = [
437
- {
438
- "role": "user",
439
- "content": prompt
440
- }
441
- ]
442
-
443
- client = OpenAI(
444
- base_url="https://router.huggingface.co/novita",
445
- api_key=HF_API_KEY,
446
- )
447
-
448
- completion = client.chat.completions.create(
449
- model="deepseek/deepseek-r1-distill-qwen-14b",
450
- messages=messages,
451
- )
452
-
453
- price_list = re.sub(r"<think>.*?</think>\s*", "", completion.choices[0].message.content, flags=re.DOTALL)
454
-
455
- price_list = re.sub(r"^```json\n|```$", "", price_list, flags=re.DOTALL)
456
-
457
- print(price_list)
458
-
459
- def json_to_excel(contract_summary, json_data, excel_path):
460
- """Converts extracted JSON tables to an Excel file."""
461
-
462
- # Correctly parse the JSON string
463
- contract_summary_json = json.loads(json.loads(contract_summary))
464
-
465
- print(contract_summary_json)
466
-
467
- contract_summary_df = pd.DataFrame([contract_summary_json])
468
-
469
- # Ensure json_data is a dictionary
470
- if isinstance(json_data, str):
471
- json_data = json.loads(json_data)
472
-
473
- long_tables = [pd.DataFrame(table) for key, table in json_data.items() if "long_table" in key and "summary" not in key]
474
- long_table = long_tables[-1] if long_tables else pd.DataFrame()
475
-
476
- with pd.ExcelWriter(excel_path) as writer:
477
- contract_summary_df.to_excel(writer, sheet_name="Contract Summary", index=False)
478
- long_table.to_excel(writer, sheet_name="Price List", index=False)
479
-
480
- #--- Extract PO ------------------------------
481
-
482
- def extract_po(docx_path):
483
- """Processes a single .docx file, extracts tables, formats with OpenAI, and saves as an Excel file."""
484
- if not os.path.exists(docx_path) or not docx_path.endswith(".docx"):
485
- print(f"Invalid file: {docx_path}")
486
- return
487
-
488
- # Read the .docx file as bytes
489
- with open(docx_path, "rb") as f:
490
- docx_bytes = BytesIO(f.read())
491
-
492
- # Step 1: Extract XML content from DOCX
493
- print("Extracting Docs data to XML...")
494
- xml_file = extract_docx_as_xml(docx_bytes,save_xml=True)
495
-
496
- get_namespace(ET.fromstring(xml_file))
497
-
498
- # Step 2: Extract tables from DOCX and save JSON
499
- print("Extracting XML data to JSON...")
500
- extracted_data = xml_to_json(xml_file, save_json=True)
501
-
502
- # Step 2: Process JSON with OpenAI to get structured output
503
- print("Processing JSON data with AI...")
504
- contract_summary = deepseek_extract_contract_summary(extracted_data, save_json=True)
505
-
506
- # Step 3: Save formatted data as Excel
507
- print("Converting AI Generated JSON to Excel...")
508
- excel_output_path = os.path.splitext(docx_path)[0] + ".xlsx"
509
- json_to_excel(contract_summary, extracted_data, excel_output_path)
510
-
511
- print(f"Excel file saved at: {excel_output_path}")
512
-
513
-
514
- # Logging
515
- log = f"""Results:
516
-
517
- Contract Summary: {contract_summary},
518
-
519
- RAW Extracted Data: {extracted_data},
520
-
521
- XML Preview: {xml_file[:1000]}"""
522
-
523
- print(log)
524
-
525
- logging.info(f"""{log}""")
526
-
527
-
528
- return excel_output_path
529
-
530
- # Example Usage
531
-
532
- # extract_po("test-contract-converted.docx")
533
- # extract_po("test-contract.docx")
534
-
535
- # Gradio Interface ------------------------------
536
-
537
- import gradio as gr
538
- from gradio.themes.base import Base
539
-
540
- interface = gr.Interface(
541
- fn=extract_po,
542
- title="PO Extractor 买卖合同数据提取",
543
- inputs=gr.File(label="买卖合同 (.docx)"),
544
- outputs=gr.File(label="数据提取结果 (.xlsx)"),
545
- allow_flagging="never",
546
- theme=Base()
547
- )
548
-
549
- interface.launch()
 
1
+ import os
2
+
3
+ import json
4
+ import pandas as pd
5
+
6
+ import zipfile
7
+ import xml.etree.ElementTree as ET
8
+ from io import BytesIO
9
+
10
+ from openai import OpenAI
11
+
12
+ import re
13
+
14
+ import logging
15
+
16
+ # Configure logging to write to 'zaoju_logs.log' without using pickle
17
+ logging.basicConfig(
18
+ filename='extract_po_logs.log',
19
+ level=logging.INFO,
20
+ format='%(asctime)s - %(levelname)s - %(message)s',
21
+ encoding='utf-8'
22
+ )
23
+
24
+ # Default Word XML namespace
25
+ DEFAULT_NS = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
26
+ NS = None # Global variable to store the namespace
27
+
28
+ def get_namespace(root):
29
+ """Extracts the primary namespace from the XML root element while keeping the default."""
30
+ global NS
31
+
32
+ if NS is None:
33
+ ns = root.tag.split('}')[0].strip('{')
34
+ NS = {'w': ns} if ns else DEFAULT_NS
35
+ return NS
36
+
37
+ # --- Helper Functions for DOCX Processing ---
38
+
39
+ def extract_text_from_cell(cell):
40
+ """Extracts text from a Word table cell, preserving line breaks and reconstructing split words."""
41
+ paragraphs = cell.findall('.//w:p', NS)
42
+ lines = []
43
+
44
+ for paragraph in paragraphs:
45
+ # Get all text runs and concatenate their contents
46
+ text_runs = [t.text for t in paragraph.findall('.//w:t', NS) if t.text]
47
+ line = ''.join(text_runs).strip() # Merge split words properly
48
+
49
+ if line: # Add only non-empty lines
50
+ lines.append(line)
51
+
52
+ return lines # Return list of lines to preserve line breaks
53
+
54
+ def clean_spaces(text):
55
+ """
56
+ Removes excessive spaces between Chinese characters while preserving spaces in English words.
57
+ """
58
+ # Remove spaces **between** Chinese characters but keep English spaces
59
+ text = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', text)
60
+ return text.strip()
61
+
62
+ def extract_key_value_pairs(text, target_dict=None):
63
+ """
64
+ Extracts multiple key-value pairs from a given text.
65
+ - First, split by more than 3 spaces (`\s{3,}`) **only if the next segment contains a `:`.**
66
+ - Then, process each segment by splitting at `:` to correctly assign keys and values.
67
+ """
68
+ if target_dict is None:
69
+ target_dict = {}
70
+
71
+ text = text.replace("", ":") # Normalize Chinese colons to English colons
72
+
73
+ # Step 1: Check if splitting by more than 3 spaces is necessary
74
+ segments = re.split(r'(\s{3,})', text) # Use raw string to prevent invalid escape sequence
75
+
76
+ # Step 2: Process each segment, ensuring we only split if the next part has a `:`
77
+ merged_segments = []
78
+ temp_segment = ""
79
+
80
+ for segment in segments:
81
+ if ":" in segment: # If segment contains `:`, it's a valid split point
82
+ if temp_segment:
83
+ merged_segments.append(temp_segment.strip())
84
+ temp_segment = ""
85
+ merged_segments.append(segment.strip())
86
+ else:
87
+ temp_segment += " " + segment.strip()
88
+
89
+ if temp_segment:
90
+ merged_segments.append(temp_segment.strip())
91
+
92
+ # Step 3: Extract key-value pairs correctly
93
+ for segment in merged_segments:
94
+ if ':' in segment:
95
+ key, value = segment.split(':', 1) # Only split at the first colon
96
+ key, value = key.strip(), value.strip() # Clean spaces
97
+
98
+ if key in target_dict:
99
+ target_dict[key] += "\n" + value # Append if key already exists
100
+ else:
101
+ target_dict[key] = value
102
+
103
+ return target_dict
104
+
105
+ # --- Table Processing Functions ---
106
+
107
+ def process_single_column_table(rows):
108
+ """Processes a single-column table and returns the extracted lines as a list."""
109
+ single_column_data = []
110
+
111
+ for row in rows:
112
+ cells = row.findall('.//w:tc', NS)
113
+ if len(cells) == 1:
114
+ cell_lines = extract_text_from_cell(cells[0]) # Extract all lines from the cell
115
+
116
+ # Append each line directly to the list without splitting
117
+ single_column_data.extend(cell_lines)
118
+
119
+ return single_column_data # Return the list of extracted lines
120
+
121
+ def process_buyer_seller_table(rows):
122
+ """Processes a two-column buyer-seller table into a structured dictionary using the first row as keys."""
123
+ headers = [extract_text_from_cell(cell) for cell in rows[0].findall('.//w:tc', NS)]
124
+ if len(headers) != 2:
125
+ return None # Not a buyer-seller table
126
+
127
+ # determine role based on header text
128
+ def get_role(header_text, default_role):
129
+ header_text = header_text.lower() # Convert to lowercase
130
+ if '买方' in header_text or 'buyer' in header_text or '甲方' in header_text:
131
+ return 'buyer_info'
132
+ elif '卖方' in header_text or 'seller' in header_text or '乙方' in header_text:
133
+ return 'seller_info'
134
+ else:
135
+ return default_role # Default if no keyword is found
136
+
137
+ # Determine the keys for buyer and seller columns
138
+ buyer_key = get_role(headers[0][0], 'buyer_info')
139
+ seller_key = get_role(headers[1][0], 'seller_info')
140
+
141
+ # Initialize the dictionary using the determined keys
142
+ buyer_seller_data = {
143
+ buyer_key: {},
144
+ seller_key: {}
145
+ }
146
+
147
+ for row in rows:
148
+ cells = row.findall('.//w:tc', NS)
149
+ if len(cells) == 2:
150
+ buyer_lines = extract_text_from_cell(cells[0])
151
+ seller_lines = extract_text_from_cell(cells[1])
152
+
153
+ for line in buyer_lines:
154
+ extract_key_value_pairs(line, buyer_seller_data[buyer_key])
155
+
156
+ for line in seller_lines:
157
+ extract_key_value_pairs(line, buyer_seller_data[seller_key])
158
+
159
+ return buyer_seller_data
160
+
161
+ def process_summary_table(rows):
162
+ """Processes a two-column summary table where keys are extracted as dictionary keys."""
163
+ extracted_data = []
164
+
165
+ for row in rows:
166
+ cells = row.findall('.//w:tc', NS)
167
+ if len(cells) == 2:
168
+ key = " ".join(extract_text_from_cell(cells[0]))
169
+ value = " ".join(extract_text_from_cell(cells[1]))
170
+ extracted_data.append({key: value})
171
+
172
+ return extracted_data
173
+
174
+ def extract_headers(first_row_cells):
175
+ """Extracts unique column headers from the first row of a table."""
176
+ headers = []
177
+ header_count = {}
178
+ for cell in first_row_cells:
179
+ cell_text = " ".join(extract_text_from_cell(cell))
180
+ grid_span = cell.find('.//w:gridSpan', NS)
181
+ col_span = int(grid_span.attrib.get(f'{{{NS["w"]}}}val', '1')) if grid_span is not None else 1
182
+ for _ in range(col_span):
183
+ # Ensure header uniqueness by appending an index if repeated
184
+ if cell_text in header_count:
185
+ header_count[cell_text] += 1
186
+ unique_header = f"{cell_text}_{header_count[cell_text]}"
187
+ else:
188
+ header_count[cell_text] = 1
189
+ unique_header = cell_text
190
+ headers.append(unique_header if unique_header else f"Column_{len(headers) + 1}")
191
+ return headers
192
+
193
+ def process_long_table(rows):
194
+ """Processes a standard table and correctly handles horizontally merged cells."""
195
+ if not rows:
196
+ return [] # Avoid IndexError
197
+
198
+ headers = extract_headers(rows[0].findall('.//w:tc', NS))
199
+ table_data = []
200
+ vertical_merge_tracker = {}
201
+
202
+ for row in rows[1:]:
203
+ row_data = {}
204
+ cells = row.findall('.//w:tc', NS)
205
+ running_index = 0
206
+
207
+ for cell in cells:
208
+ cell_text = " ".join(extract_text_from_cell(cell))
209
+
210
+ # Consistent Namespace Handling for Horizontal Merge
211
+ grid_span = cell.find('.//w:gridSpan', NS)
212
+ grid_span_val = grid_span.attrib.get(f'{{{NS["w"]}}}val') if grid_span is not None else '1'
213
+ col_span = int(grid_span_val)
214
+
215
+ # Handle vertical merge
216
+ v_merge = cell.find('.//w:vMerge', NS)
217
+ if v_merge is not None:
218
+ v_merge_val = v_merge.attrib.get(f'{{{NS["w"]}}}val')
219
+ if v_merge_val == 'restart':
220
+ vertical_merge_tracker[running_index] = cell_text
221
+ else:
222
+ # Repeat the value from the previous row's merged cell
223
+ cell_text = vertical_merge_tracker.get(running_index, "")
224
+
225
+ # Repeat the value for horizontally merged cells
226
+ start_col = running_index
227
+ end_col = running_index + col_span
228
+
229
+ # Repeat the value for each spanned column
230
+ for col in range(start_col, end_col):
231
+ key = headers[col] if col < len(headers) else f"Column_{col+1}"
232
+ row_data[key] = cell_text
233
+
234
+ # Update the running index to the end of the merged cell
235
+ running_index = end_col
236
+
237
+ # Fill remaining columns with empty strings to maintain alignment
238
+ while running_index < len(headers):
239
+ row_data[headers[running_index]] = ""
240
+ running_index += 1
241
+
242
+ table_data.append(row_data)
243
+
244
+ return table_data
245
+
246
+ def extract_tables(root):
247
+ """Extracts tables from the DOCX document and returns structured data."""
248
+ tables = root.findall('.//w:tbl', NS)
249
+ table_data = {}
250
+ table_paragraphs = set()
251
+
252
+ for table_index, table in enumerate(tables, start=1):
253
+ rows = table.findall('.//w:tr', NS)
254
+ if not rows:
255
+ continue # Skip empty tables
256
+
257
+ for paragraph in table.findall('.//w:p', NS):
258
+ table_paragraphs.add(paragraph)
259
+
260
+ first_row_cells = rows[0].findall('.//w:tc', NS)
261
+ num_columns = len(first_row_cells)
262
+
263
+ if num_columns == 1:
264
+ single_column_data = process_single_column_table(rows)
265
+ if single_column_data:
266
+ table_data[f"table_{table_index}_single_column"] = single_column_data
267
+ continue # Skip further processing for this table
268
+
269
+ summary_start_index = None
270
+ for i, row in enumerate(rows):
271
+ if len(row.findall('.//w:tc', NS)) == 2:
272
+ summary_start_index = i
273
+ break
274
+
275
+ long_table_data = []
276
+ summary_data = []
277
+
278
+ if summary_start_index is not None and summary_start_index > 0:
279
+ long_table_data = process_long_table(rows[:summary_start_index])
280
+ elif summary_start_index is None:
281
+ long_table_data = process_long_table(rows)
282
+
283
+ if summary_start_index is not None:
284
+ is_buyer_seller_table = all(len(row.findall('.//w:tc', NS)) == 2 for row in rows)
285
+ if is_buyer_seller_table:
286
+ buyer_seller_data = process_buyer_seller_table(rows)
287
+ if buyer_seller_data:
288
+ table_data[f"table_{table_index}_buyer_seller"] = buyer_seller_data
289
+ else:
290
+ summary_data = process_summary_table(rows[summary_start_index:])
291
+
292
+ if long_table_data:
293
+ table_data[f"long_table_{table_index}"] = long_table_data
294
+ if summary_data:
295
+ table_data[f"long_table_{table_index}_summary"] = summary_data
296
+
297
+ return table_data, table_paragraphs
298
+
299
+ # --- Non-Table Processing Functions ---
300
+
301
+ def extract_text_outside_tables(root, table_paragraphs):
302
+ """Extracts text from paragraphs outside tables in the document."""
303
+ extracted_text = []
304
+
305
+ # print(ET.tostring(root, encoding='unicode'))
306
+ for paragraph in root.findall('.//w:p', NS):
307
+ if paragraph in table_paragraphs:
308
+ continue # Skip paragraphs inside tables
309
+
310
+ texts = [t.text.strip() for t in paragraph.findall('.//w:t', NS) if t.text]
311
+ line = clean_spaces(' '.join(texts).replace(';', '').replace(';','').replace(':',':')) # Remove semicolons and clean spaces
312
+
313
+ if ':' in line:
314
+ extracted_text.append(line)
315
+
316
+ return extracted_text
317
+
318
+ # --- Main Extraction Functions ---
319
+
320
+ def extract_docx_as_xml(file_bytes, save_xml=False, xml_filename="document.xml"):
321
+
322
+ # Ensure file_bytes is at the start position
323
+ file_bytes.seek(0)
324
+
325
+ with zipfile.ZipFile(file_bytes, 'r') as docx:
326
+ with docx.open('word/document.xml') as xml_file:
327
+ xml_content = xml_file.read().decode('utf-8')
328
+ if save_xml:
329
+ with open(xml_filename, "w", encoding="utf-8") as f:
330
+ f.write(xml_content)
331
+ return xml_content
332
+
333
+ def xml_to_json(xml_content, save_json=False, json_filename="extracted_data.json"):
334
+
335
+ tree = ET.ElementTree(ET.fromstring(xml_content))
336
+ root = tree.getroot()
337
+
338
+ table_data, table_paragraphs = extract_tables(root)
339
+ extracted_data = table_data
340
+ extracted_data["non_table_data"] = extract_text_outside_tables(root, table_paragraphs)
341
+
342
+ if save_json:
343
+ with open(json_filename, "w", encoding="utf-8") as f:
344
+ json.dump(extracted_data, f, ensure_ascii=False, indent=4)
345
+
346
+ return json.dumps(extracted_data, ensure_ascii=False, indent=4)
347
+
348
+ def deepseek_extract_contract_summary(json_data, save_json=False):
349
+ """Sends extracted JSON data to OpenAI and returns formatted structured JSON."""
350
+
351
+ # Step 1: Convert JSON string to Python dictionary
352
+ contract_data = json.loads(json_data)
353
+
354
+ # Step 2: Remove keys that contain "long_table"
355
+ filtered_contract_data = {key: value for key, value in contract_data.items() if "long_table" not in key}
356
+
357
+ # Step 3: Convert back to JSON string (if needed)
358
+ json_output = json.dumps(filtered_contract_data, ensure_ascii=False, indent=4)
359
+
360
+ prompt = """You are given a contract in JSON format. Extract the following information:
361
+
362
+ # Response Format
363
+ Return the extracted information as a structured JSON in the exact format shown below (Do not repeat any keys):
364
+
365
+ {
366
+ "合同编号":
367
+ "采购经办人":
368
+ "接收人":
369
+ "Recipient":
370
+ "接收地":
371
+ "Place of receipt":
372
+ "供应商":
373
+ "币种":
374
+ "合同日期":
375
+ "供货日期":
376
+ }
377
+
378
+ Contract data in JSON format:""" + f"""
379
+ {json_output}"""
380
+
381
+ messages = [
382
+ {
383
+ "role": "user",
384
+ "content": prompt
385
+ }
386
+ ]
387
+
388
+ client = OpenAI(
389
+ base_url="https://router.huggingface.co/novita",
390
+ api_key=HF_API_KEY,
391
+ )
392
+
393
+ completion = client.chat.completions.create(
394
+ model="deepseek/deepseek-r1-distill-qwen-14b",
395
+ messages=messages,
396
+ )
397
+
398
+ contract_summary = re.sub(r"<think>.*?</think>\s*", "", completion.choices[0].message.content, flags=re.DOTALL) # Remove think
399
+
400
+ contract_summary = re.sub(r"^```json\n|```$", "", contract_summary, flags=re.DOTALL) # Remove ```
401
+
402
+ if save_json:
403
+ with open("extracted_contract_summary.json", "w", encoding="utf-8") as f:
404
+ f.write(contract_summary)
405
+
406
+ return json.dumps(contract_summary, ensure_ascii=False, indent=4)
407
+
408
+ def deepseek_extract_price_list(json_data):
409
+ """Sends extracted JSON data to OpenAI and returns formatted structured JSON."""
410
+
411
+ # Step 1: Convert JSON string to Python dictionary
412
+ contract_data = json.loads(json_data)
413
+
414
+ # Step 2: Remove keys that contain "long_table"
415
+ filtered_contract_data = {key: value for key, value in contract_data.items() if "long_table" in key}
416
+
417
+ # Step 3: Convert back to JSON string (if needed)
418
+ json_output = json.dumps(filtered_contract_data, ensure_ascii=False, indent=4)
419
+
420
+ print(json_output)
421
+
422
+ prompt = """You are given a price list in JSON format. Extract the following information in CSV format:
423
+
424
+ # Response Format
425
+ Return the extracted information as a CSV in the exact format shown below:
426
+
427
+ 物料名称, 物料名称(英文), 物料规格, 采购数量, 单位, 单价, 计划号
428
+
429
+ JSON data:""" + f"""
430
+ {json_output}"""
431
+
432
+ messages = [
433
+ {
434
+ "role": "user",
435
+ "content": prompt
436
+ }
437
+ ]
438
+
439
+ client = OpenAI(
440
+ base_url="https://router.huggingface.co/novita",
441
+ api_key=HF_API_KEY,
442
+ )
443
+
444
+ completion = client.chat.completions.create(
445
+ model="deepseek/deepseek-r1-distill-qwen-14b",
446
+ messages=messages,
447
+ )
448
+
449
+ price_list = re.sub(r"<think>.*?</think>\s*", "", completion.choices[0].message.content, flags=re.DOTALL)
450
+
451
+ price_list = re.sub(r"^```json\n|```$", "", price_list, flags=re.DOTALL)
452
+
453
+ print(price_list)
454
+
455
+ def json_to_excel(contract_summary, json_data, excel_path):
456
+ """Converts extracted JSON tables to an Excel file."""
457
+
458
+ # Correctly parse the JSON string
459
+ contract_summary_json = json.loads(json.loads(contract_summary))
460
+
461
+ print(contract_summary_json)
462
+
463
+ contract_summary_df = pd.DataFrame([contract_summary_json])
464
+
465
+ # Ensure json_data is a dictionary
466
+ if isinstance(json_data, str):
467
+ json_data = json.loads(json_data)
468
+
469
+ long_tables = [pd.DataFrame(table) for key, table in json_data.items() if "long_table" in key and "summary" not in key]
470
+ long_table = long_tables[-1] if long_tables else pd.DataFrame()
471
+
472
+ with pd.ExcelWriter(excel_path) as writer:
473
+ contract_summary_df.to_excel(writer, sheet_name="Contract Summary", index=False)
474
+ long_table.to_excel(writer, sheet_name="Price List", index=False)
475
+
476
+ #--- Extract PO ------------------------------
477
+
478
+ def extract_po(docx_path):
479
+ """Processes a single .docx file, extracts tables, formats with OpenAI, and saves as an Excel file."""
480
+ if not os.path.exists(docx_path) or not docx_path.endswith(".docx"):
481
+ print(f"Invalid file: {docx_path}")
482
+ return
483
+
484
+ # Read the .docx file as bytes
485
+ with open(docx_path, "rb") as f:
486
+ docx_bytes = BytesIO(f.read())
487
+
488
+ # Step 1: Extract XML content from DOCX
489
+ print("Extracting Docs data to XML...")
490
+ xml_file = extract_docx_as_xml(docx_bytes,save_xml=True)
491
+
492
+ get_namespace(ET.fromstring(xml_file))
493
+
494
+ # Step 2: Extract tables from DOCX and save JSON
495
+ print("Extracting XML data to JSON...")
496
+ extracted_data = xml_to_json(xml_file, save_json=True)
497
+
498
+ # Step 2: Process JSON with OpenAI to get structured output
499
+ print("Processing JSON data with AI...")
500
+ contract_summary = deepseek_extract_contract_summary(extracted_data, save_json=True)
501
+
502
+ # Step 3: Save formatted data as Excel
503
+ print("Converting AI Generated JSON to Excel...")
504
+ excel_output_path = os.path.splitext(docx_path)[0] + ".xlsx"
505
+ json_to_excel(contract_summary, extracted_data, excel_output_path)
506
+
507
+ print(f"Excel file saved at: {excel_output_path}")
508
+
509
+
510
+ # Logging
511
+ log = f"""Results:
512
+
513
+ Contract Summary: {contract_summary},
514
+
515
+ RAW Extracted Data: {extracted_data},
516
+
517
+ XML Preview: {xml_file[:1000]}"""
518
+
519
+ print(log)
520
+
521
+ logging.info(f"""{log}""")
522
+
523
+
524
+ return excel_output_path
525
+
526
+ # Example Usage
527
+
528
+ # extract_po("test-contract-converted.docx")
529
+ # extract_po("test-contract.docx")
530
+
531
+ # Gradio Interface ------------------------------
532
+
533
+ import gradio as gr
534
+ from gradio.themes.base import Base
535
+
536
+ interface = gr.Interface(
537
+ fn=extract_po,
538
+ title="PO Extractor 买卖合同数据提取",
539
+ inputs=gr.File(label="买卖合同 (.docx)"),
540
+ outputs=gr.File(label="数据提取结果 (.xlsx)"),
541
+ allow_flagging="never",
542
+ theme=Base()
543
+ )
544
+
545
+ interface.launch()