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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()