Repository navigation
Expand file tree
/
Copy pathDocling-webui.py
More file actions
187 lines (159 loc) Β· 6.59 KB
/
Copy pathDocling-webui.py
File metadata and controls
187 lines (159 loc) Β· 6.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import os
import gradio as gr
from docling.document_converter import DocumentConverter
import warnings
import torch
from typing import List
from concurrent.futures import ThreadPoolExecutor, as_completed
import socket
from contextlib import closing
# Environment Configuration
os.environ.update({
'HF_HUB_DISABLE_SYMLINKS_WARNING': '1',
'KMP_DUPLICATE_LIB_OK': 'TRUE'
})
# Suppress Warnings
warnings.filterwarnings("ignore", category=UserWarning, message=".*Blowfish.*")
# Document Directory
DOCUMENTS_DIR = os.path.join(os.getcwd(), 'documents')
os.makedirs(DOCUMENTS_DIR, exist_ok=True)
# Device Configuration
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
MAX_WORKERS = min(4, os.cpu_count()) if DEVICE == "cuda" else os.cpu_count()
def generate_unique_filename(base_name: str, ext: str) -> str:
"""Generate unique filename"""
counter = 1
filename = f"{base_name}.{ext}"
filepath = os.path.join(DOCUMENTS_DIR, filename)
while os.path.exists(filepath):
filename = f"{base_name}_{counter}.{ext}"
filepath = os.path.join(DOCUMENTS_DIR, filename)
counter += 1
return filename
def process_single_file_wrapper(args):
"""Thread-safe file processing wrapper"""
file, device = args
try:
converter = DocumentConverter() # Removed device parameter
result = converter.convert(file.name)
markdown = result.document.export_to_markdown()
base_name = os.path.splitext(os.path.basename(file.name))[0]
filename = generate_unique_filename(base_name, "md")
filepath = os.path.join(DOCUMENTS_DIR, filename)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(markdown)
return {"status": "success", "filename": filename, "original": file.name}
except Exception as e:
return {"status": "error", "error": str(e), "original": file.name}
def process_documents(files: List[gr.FileData], progress=gr.Progress()):
"""Optimized document processing"""
if not files:
return "Please select at least one file to process"
results = []
processed = 0
progress(0, desc="Initializing processing environment")
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
futures = {executor.submit(process_single_file_wrapper, (file, DEVICE)): file for file in files}
progress(0, desc="Starting file processing")
for future in as_completed(futures):
processed += 1
try:
result = future.result()
results.append(result)
except Exception as e:
file = futures[future]
results.append({"status": "error", "error": str(e), "original": file.name})
progress(processed / len(files), f"Processed {processed}/{len(files)} files")
success_list = [r for r in results if r["status"] == "success"]
error_list = [r for r in results if r["status"] == "error"]
report = [
"π Processing Report Summary:",
f"β’ Total Files: {len(files)}",
f"β’ β
Successful Conversions: {len(success_list)}",
f"β’ β Failed Conversions: {len(error_list)}",
"\nπ Detailed Results:"
]
if success_list:
report.append("\nSuccessfully Converted Files:")
report.extend([f" - {res['original']} β {res['filename']}" for res in success_list])
if error_list:
report.append("\nFailed Files:")
report.extend([f" - {res['original']}: {res['error']}" for res in error_list])
return "\n".join(report)
def create_interface():
"""Create optimized interface"""
with gr.Blocks(title="Docling Document Processor") as demo:
gr.Markdown(f"""
## π Docling Document Processor
**Supported Formats**: PDF, Word, Excel, PPT, Images
**Hardware Acceleration**: {'β
CUDA Enabled' if DEVICE == 'cuda' else 'β CPU Mode'}
""")
with gr.Row():
file_input = gr.File(
label="π Batch Upload Files (Multi-select Supported)",
file_count="multiple",
file_types=[
'.pdf', '.docx', '.pptx', '.xlsx',
'.html', '.md', '.asciidoc',
'.jpg', '.png', '.jpeg', '.gif'
],
height=200
)
with gr.Row():
with gr.Column(scale=3):
output = gr.Textbox(
label="Processing Report",
interactive=False,
lines=15,
max_lines=20,
show_copy_button=True
)
with gr.Column(scale=1):
gr.Markdown("""
**User Guide**:
1. Click "Choose Files" or drag files
2. Click Start Processing
3. View results in the report panel
4. Outputs saved in `./documents`
""")
with gr.Row():
process_btn = gr.Button("π Start Batch Processing", variant="primary")
clear_btn = gr.Button("π Clear All", variant="secondary")
process_btn.click(
process_documents,
inputs=[file_input],
outputs=output,
concurrency_limit=MAX_WORKERS
)
clear_btn.click(
lambda: ["", None],
outputs=[output, file_input]
)
return demo
def find_free_port(start=7860, end=8000):
"""Find available port"""
for port in range(start, end+1):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
if s.connect_ex(('localhost', port)) != 0:
return port
raise OSError(f"No available ports between {start}-{end}")
if __name__ == "__main__":
port = find_free_port()
print(f"π Server started: http://localhost:{port}")
try:
create_interface().queue().launch(
server_port=port,
server_name="0.0.0.0",
share=False,
show_error=True,
)
except Exception as e:
print(f"β οΈ Port {port} unavailable, trying alternatives...")
port = find_free_port(7870, 7890)
create_interface().launch(
server_port=port,
server_name="0.0.0.0",
share=False
)
finally:
print(f"β
Service closed on port {port}")