Maheen001 commited on
Commit
32285b7
·
verified ·
1 Parent(s): 10bd609

Create tools/form_filler_server.py

Browse files
Files changed (1) hide show
  1. tools/form_filler_server.py +150 -0
tools/form_filler_server.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any
2
+ import json
3
+ from docx import Document
4
+ from openpyxl import load_workbook
5
+
6
+
7
+ async def fill_form(template_path: str, data: Dict[str, Any]) -> dict:
8
+ """
9
+ Auto-fill form template with extracted data
10
+
11
+ Args:
12
+ template_path: Path to form template (DOCX or XLSX)
13
+ data: Dictionary of field values
14
+
15
+ Returns:
16
+ Dict with filled form path and fields filled
17
+ """
18
+ try:
19
+ file_ext = Path(template_path).suffix.lower()
20
+ output_path = template_path.replace(file_ext, f'_filled{file_ext}')
21
+
22
+ if file_ext == '.docx':
23
+ return await fill_docx_form(template_path, data, output_path)
24
+ elif file_ext in ['.xlsx', '.xls']:
25
+ return await fill_excel_form(template_path, data, output_path)
26
+ else:
27
+ # Generic text replacement
28
+ return await fill_text_form(template_path, data, output_path)
29
+
30
+ except Exception as e:
31
+ return {'error': str(e), 'success': False}
32
+
33
+
34
+ async def fill_docx_form(template_path: str, data: Dict[str, Any], output_path: str) -> dict:
35
+ """Fill DOCX form template"""
36
+ try:
37
+ doc = Document(template_path)
38
+ fields_filled = []
39
+
40
+ # Replace in paragraphs
41
+ for paragraph in doc.paragraphs:
42
+ for key, value in data.items():
43
+ placeholder = f"{{{{{key}}}}}" # {{field_name}}
44
+ if placeholder in paragraph.text:
45
+ paragraph.text = paragraph.text.replace(placeholder, str(value))
46
+ fields_filled.append(key)
47
+
48
+ # Replace in tables
49
+ for table in doc.tables:
50
+ for row in table.rows:
51
+ for cell in row.cells:
52
+ for key, value in data.items():
53
+ placeholder = f"{{{{{key}}}}}"
54
+ if placeholder in cell.text:
55
+ cell.text = cell.text.replace(placeholder, str(value))
56
+ if key not in fields_filled:
57
+ fields_filled.append(key)
58
+
59
+ doc.save(output_path)
60
+
61
+ return {
62
+ 'success': True,
63
+ 'output_path': output_path,
64
+ 'fields_filled': fields_filled,
65
+ 'total_fields': len(fields_filled)
66
+ }
67
+
68
+ except Exception as e:
69
+ return {'error': str(e), 'success': False}
70
+
71
+
72
+ async def fill_excel_form(template_path: str, data: Dict[str, Any], output_path: str) -> dict:
73
+ """Fill Excel form template"""
74
+ try:
75
+ wb = load_workbook(template_path)
76
+ ws = wb.active
77
+ fields_filled = []
78
+
79
+ # Search for placeholders and replace
80
+ for row in ws.iter_rows():
81
+ for cell in row:
82
+ if cell.value and isinstance(cell.value, str):
83
+ for key, value in data.items():
84
+ placeholder = f"{{{{{key}}}}}"
85
+ if placeholder in cell.value:
86
+ cell.value = cell.value.replace(placeholder, str(value))
87
+ fields_filled.append(key)
88
+
89
+ wb.save(output_path)
90
+
91
+ return {
92
+ 'success': True,
93
+ 'output_path': output_path,
94
+ 'fields_filled': list(set(fields_filled)),
95
+ 'total_fields': len(set(fields_filled))
96
+ }
97
+
98
+ except Exception as e:
99
+ return {'error': str(e), 'success': False}
100
+
101
+
102
+ async def fill_text_form(template_path: str, data: Dict[str, Any], output_path: str) -> dict:
103
+ """Fill text-based form"""
104
+ try:
105
+ with open(template_path, 'r', encoding='utf-8') as f:
106
+ content = f.read()
107
+
108
+ fields_filled = []
109
+ for key, value in data.items():
110
+ placeholder = f"{{{{{key}}}}}"
111
+ if placeholder in content:
112
+ content = content.replace(placeholder, str(value))
113
+ fields_filled.append(key)
114
+
115
+ with open(output_path, 'w', encoding='utf-8') as f:
116
+ f.write(content)
117
+
118
+ return {
119
+ 'success': True,
120
+ 'output_path': output_path,
121
+ 'fields_filled': fields_filled,
122
+ 'total_fields': len(fields_filled)
123
+ }
124
+
125
+ except Exception as e:
126
+ return {'error': str(e), 'success': False}
127
+
128
+
129
+ async def generate_form_template(fields: list) -> dict:
130
+ """Generate a blank form template with specified fields"""
131
+ try:
132
+ doc = Document()
133
+ doc.add_heading('Form Template', 0)
134
+
135
+ for field in fields:
136
+ p = doc.add_paragraph()
137
+ p.add_run(f"{field}: ").bold = True
138
+ p.add_run(f"{{{{{field}}}}}")
139
+
140
+ output_path = "data/outputs/form_template.docx"
141
+ doc.save(output_path)
142
+
143
+ return {
144
+ 'success': True,
145
+ 'output_path': output_path,
146
+ 'fields': fields
147
+ }
148
+
149
+ except Exception as e:
150
+ return {'error': str(e), 'success': False}