hagras commited on
Commit
cc0151e
·
verified ·
1 Parent(s): c1a8dad

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +275 -482
server.py CHANGED
@@ -1,507 +1,300 @@
1
- import gradio as gr
2
- import tempfile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import os
 
 
4
  import uuid
5
- import logging
6
  from pathlib import Path
7
- from werkzeug.utils import secure_filename
8
- import traceback
9
- import mimetypes
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- # Import with proper error handling
 
 
12
  try:
13
  from rag_document_viewer import RAG_DV
14
- except ImportError as e:
15
- print(f"Warning: Could not import RAG_DV: {e}")
16
  RAG_DV = None
17
 
18
- # Configure logging
19
- logging.basicConfig(level=logging.INFO)
20
- logger = logging.getLogger(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- # Setup uploads directory
23
- if os.getenv("SPACE_ID"):
24
- uploads_dir = Path(tempfile.gettempdir()) / "uploads"
25
  else:
26
- uploads_dir = Path("uploads")
 
27
 
28
- uploads_dir.mkdir(exist_ok=True)
 
 
 
 
29
 
30
- # Configuration
31
- MAX_FILE_SIZE = 16 * 1024 * 1024 # 16MB
32
- ALLOWED_EXTENSIONS = {'txt', 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'odt', 'odp', 'ods'}
 
 
33
 
34
- # Global variable to store current file info for static serving
35
- current_file_info = {"uploaded_file": None, "base_path": None}
36
 
37
- def allowed_file(filename):
38
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
 
 
 
39
 
40
- def serve_static_file(filepath):
41
- """Serve static files from the RAG processing output"""
42
- try:
43
- if not current_file_info["base_path"]:
44
- return None
45
-
46
- # Clean the filepath
47
- filepath = filepath.strip('/')
48
-
49
- # Construct full path
50
- base_path = Path(current_file_info["base_path"])
51
- file_path = base_path / "rag_dv" / filepath
52
-
53
- # Security check
54
- if not file_path.exists():
55
- logger.warning(f"Static file not found: {file_path}")
56
- return None
57
-
58
- # Security check - ensure file is within expected directory
59
- if not file_path.resolve().is_relative_to(base_path.resolve()):
60
- logger.warning(f"Attempted path traversal: {file_path}")
61
- return None
62
- return str(file_path)
63
-
64
- except Exception as e:
65
- logger.error(f"Error serving static file: {e}")
66
- return None
67
-
68
- def fix_html_paths(html_content, base_url="/file="):
69
- """Fix relative paths in HTML to work with Gradio's file serving"""
70
- if not html_content or not current_file_info["base_path"]:
71
- return html_content
72
-
73
- try:
74
- base_path = Path(current_file_info["base_path"])
75
- rag_path = base_path / "rag_dv"
76
-
77
- # Replace relative asset paths with Gradio file serving paths
78
- import re
79
-
80
- # Fix CSS links
81
- css_pattern = r'href="([^"]*\.css)"'
82
- def fix_css(match):
83
- css_file = rag_path / match.group(1)
84
- if css_file.exists():
85
- return f'href="file={css_file}"'
86
- return match.group(0)
87
-
88
- html_content = re.sub(css_pattern, fix_css, html_content)
89
-
90
- # Fix JS links
91
- js_pattern = r'src="([^"]*\.js)"'
92
- def fix_js(match):
93
- js_file = rag_path / match.group(1)
94
- if js_file.exists():
95
- return f'src="file={js_file}"'
96
- return match.group(0)
97
-
98
- html_content = re.sub(js_pattern, fix_js, html_content)
99
-
100
- # Fix image sources
101
- img_pattern = r'src="(assets/[^"]*)"'
102
- def fix_img(match):
103
- img_file = rag_path / match.group(1)
104
- if img_file.exists():
105
- return f'src="file={img_file}"'
106
- return match.group(0)
107
-
108
- html_content = re.sub(img_pattern, fix_img, html_content)
109
-
110
- # Fix other asset references
111
- asset_pattern = r'"(assets/[^"]*)"'
112
- def fix_asset(match):
113
- asset_file = rag_path / match.group(1)
114
- if asset_file.exists():
115
- return f'"file={asset_file}"'
116
- return match.group(0)
117
-
118
- html_content = re.sub(asset_pattern, fix_asset, html_content)
119
-
120
- return html_content
121
-
122
- except Exception as e:
123
- logger.error(f"Error fixing HTML paths: {e}")
124
- return html_content
125
-
126
- def process_uploaded_file(file):
127
- """Process uploaded file and return status message and HTML content"""
128
- try:
129
- # Check if RAG_DV is available
130
- if RAG_DV is None:
131
- return (
132
- "❌ RAG Document Viewer is not available. Please check the installation.",
133
- None,
134
- gr.update(visible=True), # upload interface
135
- gr.update(visible=False), # content interface
136
- gr.update(visible=False) # refresh button
137
- )
138
-
139
- # Validate file
140
- if file is None:
141
- return (
142
- "❌ No file selected",
143
- None,
144
- gr.update(visible=True),
145
- gr.update(visible=False),
146
- gr.update(visible=False)
147
- )
148
-
149
- # Check file size
150
- file_size = os.path.getsize(file.name)
151
- if file_size > MAX_FILE_SIZE:
152
- return (
153
- "❌ File is too large. Maximum size is 16MB.",
154
- None,
155
- gr.update(visible=True),
156
- gr.update(visible=False),
157
- gr.update(visible=False)
158
- )
159
-
160
- # Get original filename
161
- original_filename = Path(file.name).name
162
-
163
- if not allowed_file(original_filename):
164
- return (
165
- "❌ Invalid file type. Please upload a supportedocument.",
166
- None,
167
- gr.update(visible=True),
168
- gr.update(visible=False),
169
- gr.update(visible=False)
170
- )
171
-
172
- # Generate unique filename
173
- filename = secure_filename(original_filename)
174
- if not filename:
175
- return (
176
- "❌ Invalid filename",
177
- None,
178
- gr.update(visible=True),
179
- gr.update(visible=False),
180
- gr.update(visible=False)
181
- )
182
-
183
- unique_filename = f"{uuid.uuid4()}_{filename}"
184
-
185
- # Create directory structure
186
- dir_name = Path(str(unique_filename).replace(Path(unique_filename).suffix, ""))
187
- dir_path = uploads_dir / dir_name
188
-
189
- try:
190
- dir_path.mkdir(parents=True, exist_ok=True)
191
- except OSError as e:
192
- logger.error(f"Failed to create directory {dir_path}: {e}")
193
- return (
194
- "❌ Failed to create upload directory",
195
- None,
196
- gr.update(visible=True),
197
- gr.update(visible=False),
198
- gr.update(visible=False)
199
- )
200
-
201
- file_path = dir_path / unique_filename
202
-
203
- # Copy file to new location
204
- try:
205
- import shutil
206
- shutil.copy2(file.name, str(file_path))
207
- except Exception as e:
208
- logger.error(f"Failed to save file {file_path}: {e}")
209
- return (
210
- "❌ Failed to save uploaded file",
211
- None,
212
- gr.update(visible=True),
213
- gr.update(visible=False),
214
- gr.update(visible=False)
215
- )
216
-
217
- # Verify file was saved
218
- if not file_path.exists():
219
- return (
220
- "❌ File upload failed - file not saved",
221
- None,
222
- gr.update(visible=True),
223
- gr.update(visible=False),
224
- gr.update(visible=False)
225
- )
226
-
227
- # Process with RAG_DV
228
- rag_output_path = file_path.parent / "rag_dv"
229
- try:
230
- RAG_DV(file_path, rag_output_path)
231
- except Exception as e:
232
- logger.error(f"RAG_DV processing failed: {e}")
233
- logger.error(f"Traceback: {traceback.format_exc()}")
234
-
235
- # Clean up the uploaded file if processing fails
236
- try:
237
- file_path.unlink()
238
- if dir_path.exists() and not any(dir_path.iterdir()):
239
- dir_path.rmdir()
240
- except Exception as cleanup_error:
241
- logger.error(f"Failed to cleanup after RAG_DV error: {cleanup_error}")
242
-
243
- return (
244
- "❌ Failed to process document. Please try again or use a different file.",
245
- None,
246
- gr.update(visible=True),
247
- gr.update(visible=False),
248
- gr.update(visible=False)
249
- )
250
-
251
- # Verify RAG processing created the expected output
252
- index_file = rag_output_path / "index.html"
253
- if not index_file.exists():
254
- return (
255
- "❌ Document processing incomplete. Please try again.",
256
- None,
257
- gr.update(visible=True),
258
- gr.update(visible=False),
259
- gr.update(visible=False)
260
- )
261
-
262
- # Update global file info for static serving
263
- current_file_info["uploaded_file"] = unique_filename
264
- current_file_info["base_path"] = str(file_path.parent)
265
-
266
- # Read the HTML content
267
- try:
268
- with open(index_file, 'r', encoding='utf-8') as f:
269
- html_content = f.read()
270
- except Exception as e:
271
- logger.error(f"Failed to read index file {index_file}: {e}")
272
- return (
273
- "❌ Failed to load document content",
274
- None,
275
- gr.update(visible=True),
276
- gr.update(visible=False),
277
- gr.update(visible=False)
278
- )
279
-
280
- # Fix HTML paths for Gradio file serving
281
- html_content = fix_html_paths(html_content)
282
-
283
- return (
284
- f"✅ File '{original_filename}' successfully uploaded and processed!",
285
- html_content,
286
- gr.update(visible=False), # hide upload interface
287
- gr.update(visible=True), # show content interface
288
- gr.update(visible=True) # show refresh button
289
- )
290
-
291
- except Exception as e:
292
- logger.error(f"Unexpected error in process_uploaded_file: {e}")
293
- logger.error(f"Traceback: {traceback.format_exc()}")
294
- return (
295
- "❌ Upload failed due to an unexpected error",
296
- None,
297
- gr.update(visible=True),
298
- gr.update(visible=False),
299
- gr.update(visible=False)
300
- )
301
 
302
- def refresh_session():
303
- """Reset the interface to initial state"""
304
- # Clear global file info
305
- current_file_info["uploaded_file"] = None
306
- current_file_info["base_path"] = None
307
-
308
- return (
309
- "🔄 Session refreshed. You can upload a new file.",
310
- None,
311
- gr.update(visible=True), # show upload interface
312
- gr.update(visible=False), # hide content interface
313
- gr.update(visible=False) # hide refresh button
314
- )
 
315
 
316
- def create_app():
317
- """Create the Gradio application"""
318
-
319
- # Custom CSS to match the original design
320
- custom_css = """
321
- .gradio-container {
322
- background: linear-gradient(135deg, hsla(0, 0%, 0%, 1) 0%, hsla(0, 0%, 11%, 1) 100%) !important;
323
- min-height: 100vh;
324
- color: #f3f3f3 !important;
325
- }
326
-
327
- .upload-container {
328
- background: rgba(255, 255, 255, 0.05) !important;
329
- border: 2px dashed #4a5568 !important;
330
- border-radius: 8px !important;
331
- padding: 2rem !important;
332
- text-align: center !important;
333
- transition: all 0.2s ease !important;
334
- }
335
-
336
- .upload-container:hover {
337
- border-color: #6b7280 !important;
338
- background: rgba(255, 255, 255, 0.08) !important;
339
- }
340
-
341
- .content-frame {
342
- background: rgba(255, 255, 255, 0.05) !important;
343
- border-radius: 8px !important;
344
- border: 1px solid #374151 !important;
345
- height: 80vh !important;
346
- overflow: auto !important;
347
- }
348
-
349
- .status-message {
350
- padding: 12px 20px !important;
351
- border-radius: 6px !important;
352
- margin: 10px 0 !important;
353
- font-weight: 500 !important;
354
- text-align: center !important;
355
- }
356
-
357
- .refresh-button {
358
- background: #212529 !important;
359
- color: #fff !important;
360
- border: none !important;
361
- border-radius: 6px !important;
362
- padding: 12px 20px !important;
363
- font-weight: bold !important;
364
- }
365
-
366
- .refresh-button:hover {
367
- background: #424649 !important;
368
- }
369
  """
370
-
371
- with gr.Blocks(css=custom_css, title="RAG Document Viewer Demo") as app:
372
-
373
- # Header
374
- gr.Markdown("# RAG Document Viewer Demo", elem_classes=["center"])
375
-
376
- # Status message area
377
- status_msg = gr.Markdown("", visible=False)
378
-
379
- # Upload Interface
380
- with gr.Column(visible=True) as upload_interface:
381
- gr.Markdown("""
382
- ### Upload Your Document
383
- Drop your file here or click to browse
384
- **Supports:** PDFs, Office Documents, OpenOffice Documents
385
- **Max file size:** 16MB
386
- """, elem_classes=["upload-container"])
387
-
388
- file_input = gr.File(
389
- label="Select File",
390
- file_types=[".txt", ".pdf", ".doc", ".docx", ".ppt", ".pptx",
391
- ".xls", ".xlsx", ".odt", ".odp", ".ods"],
392
- elem_classes=["upload-area"]
393
- )
394
-
395
- upload_btn = gr.Button("Upload and Process", variant="primary")
396
-
397
- # Content Interface
398
- with gr.Column(visible=False) as content_interface:
399
- with gr.Row():
400
- refresh_btn = gr.Button(
401
- "🔄 Start Over",
402
- variant="secondary",
403
- elem_classes=["refresh-button"]
404
- )
405
-
406
- # HTML content display
407
- html_display = gr.HTML(
408
- value="",
409
- elem_classes=["content-frame"]
410
- )
411
-
412
- # Refresh button (separate for better control)
413
- refresh_btn_separate = gr.Button(
414
- "🔄 Start Over",
415
- visible=False,
416
- variant="secondary",
417
- elem_classes=["refresh-button"]
418
  )
419
-
420
-
421
- # Event handlers
422
- upload_btn.click(
423
- fn=process_uploaded_file,
424
- inputs=[file_input],
425
- outputs=[
426
- status_msg,
427
- html_display,
428
- upload_interface,
429
- content_interface,
430
- refresh_btn_separate
431
- ]
432
- ).then(
433
- fn=lambda msg: gr.update(visible=bool(msg)),
434
- inputs=[status_msg],
435
- outputs=[status_msg]
436
  )
437
-
438
- # File input auto-upload (when file is selected)
439
- file_input.change(
440
- fn=process_uploaded_file,
441
- inputs=[file_input],
442
- outputs=[
443
- status_msg,
444
- html_display,
445
- upload_interface,
446
- content_interface,
447
- refresh_btn_separate
448
- ]
449
- ).then(
450
- fn=lambda msg: gr.update(visible=bool(msg)),
451
- inputs=[status_msg],
452
- outputs=[status_msg]
453
  )
454
-
455
- # Refresh handlers
456
- refresh_btn.click(
457
- fn=refresh_session,
458
- outputs=[
459
- status_msg,
460
- html_display,
461
- upload_interface,
462
- content_interface,
463
- refresh_btn_separate
464
- ]
465
- ).then(
466
- fn=lambda msg: gr.update(visible=bool(msg)),
467
- inputs=[status_msg],
468
- outputs=[status_msg]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
469
  )
470
-
471
- refresh_btn_separate.click(
472
- fn=refresh_session,
473
- outputs=[
474
- status_msg,
475
- html_display,
476
- upload_interface,
477
- content_interface,
478
- refresh_btn_separate
479
- ]
480
- ).then(
481
- fn=lambda msg: gr.update(visible=bool(msg)),
482
- inputs=[status_msg],
483
- outputs=[status_msg]
484
  )
485
-
486
- return app
487
 
488
- # Create and launch the app
489
- if __name__ == "__main__":
490
- app = create_app()
491
-
492
- # Launch configuration
493
- if os.getenv("SPACE_ID"):
494
- # Running on Hugging Face Spaces
495
- app.launch(
496
- server_name="0.0.0.0",
497
- server_port=7860,
498
- share=False,
499
- show_error=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500
  )
501
- else:
502
- # Local development
503
- app.launch(
504
- debug=True,
505
- show_error=True,
506
- share=False
507
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Flask → Gradio/FastAPI rewrite
3
+ ==============================
4
+
5
+ All behaviour (routes, template, file handling, max-size checks, RAG_DV
6
+ processing, session refresh, etc.) is preserved. Only the underlying web
7
+ framework changed – now driven by Gradio (which itself runs on FastAPI /
8
+ Uvicorn).
9
+
10
+ To install the few extra deps:
11
+
12
+ pip install gradio==4.* fastapi jinja2 python-multipart
13
+
14
+ If you used Flask’s built-in dev server before, you can still start this file
15
+ with `python app_gradio.py`, or with `uvicorn app_gradio:app --reload`.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
  import os
22
+ import tempfile
23
+ import traceback
24
  import uuid
 
25
  from pathlib import Path
26
+ from typing import List
27
+
28
+ import gradio as gr
29
+ from fastapi import (
30
+ FastAPI,
31
+ File,
32
+ HTTPException,
33
+ Request,
34
+ Response,
35
+ UploadFile,
36
+ status,
37
+ )
38
+ from fastapi.responses import HTMLResponse, RedirectResponse, FileResponse
39
+ from starlette.middleware.sessions import SessionMiddleware
40
+ from starlette.responses import PlainTextResponse
41
+ from werkzeug.utils import secure_filename # type: ignore
42
 
43
+ # --------------------------------------------------------------------------- #
44
+ # Optional RAG import (kept exactly as before) #
45
+ # --------------------------------------------------------------------------- #
46
  try:
47
  from rag_document_viewer import RAG_DV
48
+ except ImportError as err:
49
+ print(f"Warning: Could not import RAG_DV: {err}")
50
  RAG_DV = None
51
 
52
+ # --------------------------------------------------------------------------- #
53
+ # Constants & config #
54
+ # --------------------------------------------------------------------------- #
55
+ SECRET_KEY = (
56
+ "a&VhLelkAo!dKXm9o5RRHQ@#BxoI3Q5378qwFP&aJKA#PLjO7TU*Aq5Kwg4OTdMI7N3%wFAmnwezlEbPUdEQKhGJD10E8@0gSrS"
57
+ )
58
+ MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16 MB
59
+ ALLOWED_EXTENSIONS = {
60
+ "txt",
61
+ "pdf",
62
+ "doc",
63
+ "docx",
64
+ "ppt",
65
+ "pptx",
66
+ "xls",
67
+ "xlsx",
68
+ "odt",
69
+ "odp",
70
+ "ods",
71
+ }
72
 
73
+ if os.getenv("SPACE_ID"): # running inside a HF Space
74
+ UPLOADS_DIR = Path(tempfile.gettempdir()) / "uploads"
 
75
  else:
76
+ UPLOADS_DIR = Path("uploads")
77
+ UPLOADS_DIR.mkdir(exist_ok=True, parents=True)
78
 
79
+ # --------------------------------------------------------------------------- #
80
+ # Logging #
81
+ # --------------------------------------------------------------------------- #
82
+ logging.basicConfig(level=logging.INFO)
83
+ logger = logging.getLogger("rag_dv_demo")
84
 
85
+ # --------------------------------------------------------------------------- #
86
+ # Helper utilities #
87
+ # --------------------------------------------------------------------------- #
88
+ def _allowed_file(name: str) -> bool:
89
+ return "." in name and name.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
90
 
 
 
91
 
92
+ def _flash(request: Request, message: str) -> None:
93
+ """
94
+ Store a flash message in the user’s server-side session.
95
+ The template pulls them via get_flashed_messages().
96
+ """
97
+ request.session.setdefault("flash_messages", []).append(message)
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ def _redirect_with_flash(
101
+ request: Request, message: str, endpoint_name: str = "index"
102
+ ) -> Response:
103
+ _flash(request, message)
104
+ url = request.url_for(endpoint_name)
105
+ return RedirectResponse(url, status_code=status.HTTP_303_SEE_OTHER)
106
+
107
+
108
+ # --------------------------------------------------------------------------- #
109
+ # Jinja2 template (identical to original) #
110
+ # --------------------------------------------------------------------------- #
111
+ from jinja2 import Template # noqa: E402 (import after constant section)
112
+
113
+ HTML_TEMPLATE = """{{ html_source }}""" # <-- paste your original template here
114
 
115
+ # The string was abbreviated above to keep this snippet short. Please replace
116
+ # it with the *entire* HTML_TEMPLATE from your Flask application.
117
+ # --------------------------------------------------------------------------- #
118
+
119
+ template = Template(HTML_TEMPLATE)
120
+
121
+ # --------------------------------------------------------------------------- #
122
+ # FastAPI application (used by Gradio) #
123
+ # --------------------------------------------------------------------------- #
124
+ backend = FastAPI()
125
+ backend.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)
126
+
127
+
128
+ def render_template(request: Request, **ctx) -> HTMLResponse:
129
+ """
130
+ Renders the Jinja2 template, exposing session and
131
+ get_flashed_messages so the HTML stays unchanged.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  """
133
+ def _get_flashed_messages() -> List[str]:
134
+ return request.session.pop("flash_messages", [])
135
+
136
+ rendered = template.render(
137
+ session=request.session,
138
+ get_flashed_messages=_get_flashed_messages,
139
+ **ctx,
140
+ )
141
+ return HTMLResponse(rendered)
142
+
143
+
144
+ # ------------------------------ ROUTES ------------------------------------ #
145
+ @backend.get("/", name="index")
146
+ async def index(request: Request) -> Response:
147
+ return render_template(request)
148
+
149
+
150
+ @backend.post("/upload")
151
+ async def upload_file(request: Request, file: UploadFile = File(...)) -> Response:
152
+ # -- validations (mostly identical to Flask version) --------------------- #
153
+ if RAG_DV is None:
154
+ return _redirect_with_flash(
155
+ request, "RAG Document Viewer is not available. Please check the installation."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  )
157
+
158
+ if not file.filename or not _allowed_file(file.filename):
159
+ return _redirect_with_flash(
160
+ request, "Invalid file type. Please upload a supported document."
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  )
162
+
163
+ if file.size and file.size > MAX_CONTENT_LENGTH:
164
+ return _redirect_with_flash(
165
+ request, "File is too large. Maximum size is 16MB."
 
 
 
 
 
 
 
 
 
 
 
 
166
  )
167
+
168
+ filename = secure_filename(file.filename)
169
+ if not filename:
170
+ return _redirect_with_flash(request, "Invalid filename")
171
+
172
+ unique_filename = f"{uuid.uuid4()}_{filename}"
173
+ dir_name = Path(unique_filename).stem
174
+ dir_path = UPLOADS_DIR / dir_name
175
+ dir_path.mkdir(parents=True, exist_ok=True)
176
+ filepath = dir_path / unique_filename
177
+
178
+ # Save the file
179
+ try:
180
+ with open(filepath, "wb") as fout:
181
+ fout.write(await file.read())
182
+ except Exception as err:
183
+ logger.error(f"Failed saving upload: {err}")
184
+ return _redirect_with_flash(request, "Failed to save uploaded file")
185
+
186
+ # RAG_DV processing ------------------------------------------------------ #
187
+ out_path = filepath.parent / "rag_dv"
188
+ try:
189
+ RAG_DV(filepath, out_path)
190
+ except Exception as err:
191
+ logger.error(f"RAG_DV failed: {err}\n{traceback.format_exc()}")
192
+ filepath.unlink(missing_ok=True)
193
+ if not any(dir_path.iterdir()):
194
+ dir_path.rmdir()
195
+ return _redirect_with_flash(
196
+ request, "Failed to process document. Please try again."
197
  )
198
+
199
+ if not (out_path / "index.html").exists():
200
+ return _redirect_with_flash(
201
+ request, "Document processing incomplete. Please try again."
 
 
 
 
 
 
 
 
 
 
202
  )
 
 
203
 
204
+ request.session["uploaded_file"] = unique_filename
205
+ request.session["original_filename"] = filename
206
+ return _redirect_with_flash(request, "File successfully uploaded.")
207
+
208
+
209
+ @backend.get("/refresh")
210
+ async def refresh_session(request: Request) -> Response:
211
+ request.session.pop("uploaded_file", None)
212
+ request.session.pop("original_filename", None)
213
+ url = request.url_for("index")
214
+ return RedirectResponse(url, status_code=status.HTTP_303_SEE_OTHER)
215
+
216
+
217
+ @backend.get("/load/{filename:path}")
218
+ async def load(request: Request, filename: str) -> Response:
219
+ filename = secure_filename(filename)
220
+ filepath = UPLOADS_DIR / Path(filename).stem / filename
221
+ idx_file = filepath.parent / "rag_dv" / "index.html"
222
+
223
+ if not idx_file.exists():
224
+ return _redirect_with_flash(request, "Document index not found.")
225
+
226
+ with open(idx_file, "r", encoding="utf-8") as f:
227
+ html = f.read()
228
+ return HTMLResponse(html)
229
+
230
+
231
+ @backend.get("/load/assets/{asset_type}/{file_name:path}")
232
+ async def load_assets(
233
+ request: Request, asset_type: str, file_name: str
234
+ ) -> Response:
235
+ if "uploaded_file" not in request.session:
236
+ return _redirect_with_flash(request, "No active session")
237
+
238
+ asset_type = secure_filename(asset_type)
239
+ file_name = secure_filename(file_name)
240
+ base = (
241
+ UPLOADS_DIR
242
+ / Path(request.session["uploaded_file"]).stem
243
+ / "rag_dv"
244
+ / "assets"
245
+ / asset_type
246
+ )
247
+ file_path = base / file_name
248
+
249
+ if not file_path.exists():
250
+ return _redirect_with_flash(request, "Asset not found")
251
+
252
+ return FileResponse(file_path)
253
+
254
+
255
+ @backend.get("/file_size_error")
256
+ async def file_size_error(request: Request) -> Response:
257
+ _flash(request, "File size too large. Please upload a file smaller than 16MB.")
258
+ return RedirectResponse(request.url_for("index"), status_code=303)
259
+
260
+
261
+ # ----------------------------- ERROR HANDLING ----------------------------- #
262
+ @backend.exception_handler(HTTPException)
263
+ async def http_exception_handler(request: Request, exc: HTTPException):
264
+ if exc.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE:
265
+ return _redirect_with_flash(
266
+ request, "File is too large. Maximum size is 16MB."
267
  )
268
+ return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
269
+
270
+
271
+ @backend.exception_handler(Exception)
272
+ async def unhandled_exception(request: Request, exc: Exception):
273
+ logger.error(f"Unhandled error: {exc}\n{traceback.format_exc()}")
274
+ return _redirect_with_flash(
275
+ request, "An unexpected error occurred. Please try again."
276
+ )
277
+
278
+
279
+ # --------------------------------------------------------------------------- #
280
+ # Gradio mounting #
281
+ # --------------------------------------------------------------------------- #
282
+ blocks = gr.Blocks() # we don't actually need interactive components; markup
283
+ with blocks:
284
+ # Render our full HTML. Keeping it inside an <html> tag breaks the page
285
+ # (because the main / route already returns a complete document), so we
286
+ # leave the Blocks empty. Gradio is used only for its launch helper and
287
+ # FastAPI integration.
288
+ pass
289
+
290
+ app = gr.mount_gradio_app(
291
+ backend,
292
+ blocks,
293
+ path="/" # mount at root so URLs remain identical
294
+ )
295
+
296
+ # Launch via `python app_gradio.py` or `uvicorn app_gradio:app --reload`
297
+ if __name__ == "__main__":
298
+ import uvicorn
299
+
300
+ uvicorn.run("app_gradio:app", host="0.0.0.0", port=7860, reload=True)