hagras commited on
Commit
a292e96
ยท
verified ยท
1 Parent(s): 5645564

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +310 -565
server.py CHANGED
@@ -1,12 +1,11 @@
1
- from flask import Flask, request, render_template_string, session, redirect, url_for, flash, send_from_directory
2
- from pathlib import Path
 
3
  import uuid
4
  import logging
5
- import traceback
6
- import os
7
- import tempfile
8
  from werkzeug.utils import secure_filename
9
- from werkzeug.exceptions import RequestEntityTooLarge
10
 
11
  # Import with proper error handling
12
  try:
@@ -15,10 +14,11 @@ except ImportError as e:
15
  print(f"Warning: Could not import RAG_DV: {e}")
16
  RAG_DV = None
17
 
18
- app = Flask(__name__)
19
- app.secret_key = 'a&VhLelkAo!dKXm9o5RRHQ@#BxoI3Q5378qwFP&aJKA#PLjO7TU*Aq5Kwg4OTdMI7N3%wFAmnwezlEbPUdEQKhGJD10E8@0gSrS'
 
20
 
21
- # Check if we're in a Hugging Face Space
22
  if os.getenv("SPACE_ID"):
23
  uploads_dir = Path(tempfile.gettempdir()) / "uploads"
24
  else:
@@ -26,118 +26,113 @@ else:
26
 
27
  uploads_dir.mkdir(exist_ok=True)
28
 
29
- app.config['UPLOAD_FOLDER'] = uploads_dir
30
- app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
31
-
32
- # Configure logging
33
- logging.basicConfig(level=logging.INFO)
34
- logger = logging.getLogger(__name__)
35
-
36
- # Create uploads directory if it doesn't exist
37
- # app.config['UPLOAD_FOLDER'].mkdir(exist_ok=True)
38
-
39
- # Allowed file extensions
40
  ALLOWED_EXTENSIONS = {'txt', 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'odt', 'odp', 'ods'}
41
 
42
  def allowed_file(filename):
43
  return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
44
 
45
- def safe_flash_and_redirect(message, endpoint='index'):
46
- """Safely flash a message and redirect, handling any errors"""
47
- try:
48
- flash(message)
49
- return redirect(url_for(endpoint))
50
- except Exception as e:
51
- logger.error(f"Error in flash_and_redirect: {e}")
52
- # Fallback without flash if flash fails
53
- return redirect(url_for(endpoint))
54
-
55
- # Error handler for file too large
56
- @app.errorhandler(RequestEntityTooLarge)
57
- def handle_file_too_large(error):
58
- logger.warning("File upload too large attempted")
59
- return safe_flash_and_redirect('File is too large. Maximum size is 16MB.')
60
-
61
- # Error handler for internal server errors (500)
62
- @app.errorhandler(500)
63
- def handle_internal_error(error):
64
- logger.error(f"Internal server error: {error}")
65
- logger.error(f"Traceback: {traceback.format_exc()}")
66
- return safe_flash_and_redirect('An internal server error occurred. Please try again.')
67
-
68
- # Error handler for 404 errors
69
- @app.errorhandler(404)
70
- def handle_not_found(error):
71
- logger.warning(f"404 error: {error}")
72
- return safe_flash_and_redirect('Page not found.')
73
-
74
- # Error handler for general exceptions
75
- @app.errorhandler(Exception)
76
- def handle_general_exception(error):
77
- logger.error(f"Unhandled exception: {error}")
78
- logger.error(f"Traceback: {traceback.format_exc()}")
79
-
80
- # Don't handle HTTP exceptions here (let Flask handle them)
81
- if hasattr(error, 'code'):
82
- return error
83
-
84
- return safe_flash_and_redirect('An unexpected error occurred. Please try again.')
85
-
86
- @app.route('/')
87
- def index():
88
- try:
89
- return render_template_string(HTML_TEMPLATE)
90
- except Exception as e:
91
- logger.error(f"Error rendering index template: {e}")
92
- return safe_flash_and_redirect('Error loading page. Please refresh.')
93
-
94
- @app.route('/upload', methods=['POST'])
95
- def upload_file():
96
  try:
97
  # Check if RAG_DV is available
98
  if RAG_DV is None:
99
- return safe_flash_and_redirect('RAG Document Viewer is not available. Please check the installation.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
- # Validate request
102
- if 'file' not in request.files:
103
- return safe_flash_and_redirect('No file selected')
 
 
 
 
 
 
 
104
 
105
- file = request.files['file']
106
- if file.filename == '' or file.filename is None:
107
- return safe_flash_and_redirect('No file selected')
108
 
109
- if not allowed_file(file.filename):
110
- return safe_flash_and_redirect('Invalid file type. Please upload a supported document.')
 
 
 
 
 
 
111
 
112
- # Generate unique filename to avoid conflicts
113
- filename = secure_filename(file.filename)
114
  if not filename:
115
- return safe_flash_and_redirect('Invalid filename')
 
 
 
 
 
 
116
 
117
  unique_filename = f"{uuid.uuid4()}_{filename}"
118
 
119
  # Create directory structure
120
  dir_name = Path(str(unique_filename).replace(Path(unique_filename).suffix, ""))
121
- dir_path = Path(app.config['UPLOAD_FOLDER']) / dir_name
122
 
123
  try:
124
  dir_path.mkdir(parents=True, exist_ok=True)
125
  except OSError as e:
126
  logger.error(f"Failed to create directory {dir_path}: {e}")
127
- return safe_flash_and_redirect('Failed to create upload directory')
 
 
 
 
 
 
128
 
129
  file_path = dir_path / unique_filename
130
 
131
- # Save file with error handling
132
  try:
133
- file.save(str(file_path))
 
134
  except Exception as e:
135
  logger.error(f"Failed to save file {file_path}: {e}")
136
- return safe_flash_and_redirect('Failed to save uploaded file')
 
 
 
 
 
 
137
 
138
  # Verify file was saved
139
  if not file_path.exists():
140
- return safe_flash_and_redirect('File upload failed - file not saved')
 
 
 
 
 
 
141
 
142
  # Process with RAG_DV
143
  rag_output_path = file_path.parent / "rag_dv"
@@ -155,500 +150,250 @@ def upload_file():
155
  except Exception as cleanup_error:
156
  logger.error(f"Failed to cleanup after RAG_DV error: {cleanup_error}")
157
 
158
- return safe_flash_and_redirect('Failed to process document. Please try again or use a different file.')
 
 
 
 
 
 
159
 
160
  # Verify RAG processing created the expected output
161
  index_file = rag_output_path / "index.html"
162
  if not index_file.exists():
163
- return safe_flash_and_redirect('Document processing incomplete. Please try again.')
164
-
165
- # Store in session
166
- session['uploaded_file'] = unique_filename
167
- session['original_filename'] = filename
168
-
169
- return safe_flash_and_redirect('File successfully uploaded.')
170
-
171
- except Exception as e:
172
- logger.error(f"Unexpected error in upload_file: {e}")
173
- logger.error(f"Traceback: {traceback.format_exc()}")
174
- return safe_flash_and_redirect('Upload failed due to an unexpected error')
175
-
176
- @app.route('/refresh')
177
- def refresh():
178
- try:
179
- # Clear session data
180
- session.pop('uploaded_file', None)
181
- session.pop('original_filename', None)
182
- return redirect(url_for('index'))
183
- except Exception as e:
184
- logger.error(f"Error in refresh: {e}")
185
- return safe_flash_and_redirect('Error refreshing session')
186
-
187
- @app.route('/load/<filename>')
188
- def load(filename):
189
- try:
190
- if not filename:
191
- return safe_flash_and_redirect('Invalid filename')
192
-
193
- # Sanitize filename
194
- filename = secure_filename(filename)
195
- file_path = Path(app.config['UPLOAD_FOLDER']) / Path(filename).stem / filename
196
-
197
- if not file_path.exists():
198
- logger.warning(f"Attempted to load non-existent file: {file_path}")
199
- return safe_flash_and_redirect('File not found')
200
-
201
- index_file = file_path.parent / "rag_dv" / "index.html"
202
- if not index_file.exists():
203
- logger.warning(f"RAG index file not found: {index_file}")
204
- return safe_flash_and_redirect('Document index not found. Please re-upload the file.')
205
 
 
206
  try:
207
  with open(index_file, 'r', encoding='utf-8') as f:
208
- content = f.read()
209
  except Exception as e:
210
  logger.error(f"Failed to read index file {index_file}: {e}")
211
- return safe_flash_and_redirect('Failed to load document content')
 
 
 
 
 
 
212
 
213
- return render_template_string(content)
 
 
 
 
 
 
214
 
215
  except Exception as e:
216
- logger.error(f"Unexpected error in load: {e}")
217
  logger.error(f"Traceback: {traceback.format_exc()}")
218
- return safe_flash_and_redirect('Error loading document')
219
-
220
- @app.route('/load/assets/<asset_type>/<filename>')
221
- def load_assets(asset_type, filename):
222
- try:
223
- if 'uploaded_file' not in session:
224
- return safe_flash_and_redirect('No active session')
225
-
226
- # Sanitize inputs
227
- asset_type = secure_filename(asset_type)
228
- filename = secure_filename(filename)
229
-
230
- if not asset_type or not filename:
231
- return safe_flash_and_redirect('Invalid asset path')
232
-
233
- file_path = (Path(app.config['UPLOAD_FOLDER']) /
234
- Path(session['uploaded_file']).stem /
235
- "rag_dv" / "assets" / asset_type / filename)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
- if not file_path.exists():
238
- logger.warning(f"Asset not found: {file_path}")
239
- return safe_flash_and_redirect('Asset not found')
240
 
241
- # Security check - ensure file is within expected directory
242
- upload_base = Path(app.config['UPLOAD_FOLDER']).resolve()
243
- if not file_path.resolve().is_relative_to(upload_base):
244
- logger.warning(f"Attempted path traversal: {file_path}")
245
- return safe_flash_and_redirect('Invalid file path')
246
 
247
- return send_from_directory(str(file_path.parent), filename)
 
248
 
249
- except Exception as e:
250
- logger.error(f"Error loading asset: {e}")
251
- logger.error(f"Traceback: {traceback.format_exc()}")
252
- return safe_flash_and_redirect('Error loading asset')
253
-
254
- # Add new route for file size error
255
- @app.route('/file_size_error')
256
- def file_size_error():
257
- flash('File size too large. Please upload a file smaller than 16MB.')
258
- return redirect(url_for('index'))
259
-
260
- # HTML Template
261
- HTML_TEMPLATE = '''
262
- <!DOCTYPE html>
263
- <html lang="en">
264
- <head>
265
- <meta charset="UTF-8">
266
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
267
- <title>File Upload Demo</title>
268
- <style>
269
- * {
270
- margin: 0;
271
- padding: 0;
272
- box-sizing: border-box;
273
- font-family: 'Helvetica Neue', Arial, sans-serif;
274
- }
275
-
276
- body {
277
- background: -webkit-linear-gradient(135deg, hsla(0, 0%, 0%, 1) 0%, hsla(0, 0%, 11%, 1) 100%);
278
- background: linear-gradient(135deg, hsla(0, 0%, 0%, 1) 0%, hsla(0, 0%, 11%, 1) 100%);
279
- background-attachment: fixed;
280
- min-height: 100vh;
281
- position: relative;
282
- color: #f3f3f3;
283
- line-height: 1.6;
284
- }
285
-
286
- .container {
287
- max-width: 800px;
288
- margin: 0 auto;
289
- padding: 20px;
290
- }
291
-
292
- /* Upload Area Styles */
293
- .upload-container {
294
- display: flex;
295
- align-items: center;
296
- justify-content: center;
297
- min-height: 100vh;
298
- }
299
-
300
- .upload-area {
301
- width: 100%;
302
- max-width: 500px;
303
- height: 300px;
304
- border: 2px dashed #4a5568;
305
- border-radius: 8px;
306
- background: rgba(255, 255, 255, 0.05);
307
- display: flex;
308
- flex-direction: column;
309
- align-items: center;
310
- justify-content: center;
311
- cursor: pointer;
312
- transition: all 0.2s ease;
313
- position: relative;
314
- overflow: hidden;
315
- padding: 0 2rem;
316
- margin: 0 1rem;
317
- }
318
-
319
- .upload-area:hover {
320
- border-color: #6b7280;
321
- background: rgba(255, 255, 255, 0.08);
322
- }
323
-
324
- .upload-area.dragover {
325
- border-color: #9ca3af;
326
- background: rgba(255, 255, 255, 0.1);
327
- transform: translateY(-2px);
328
- box-shadow: 0 4px 16px rgba(255, 255, 255, 0.1);
329
- }
330
-
331
- .upload-icon {
332
- font-size: 48px;
333
- color: #9ca3af;
334
- margin-bottom: 20px;
335
- }
336
-
337
- .upload-text {
338
- font-size: 18px;
339
- color: #f3f3f3;
340
- margin-bottom: 10px;
341
- font-weight: 500;
342
- }
343
-
344
- .upload-subtext {
345
- font-size: 14px;
346
- color: #9ca3af;
347
- text-align: center;
348
- }
349
-
350
- .file-input {
351
- display: none;
352
- }
353
-
354
- /* Content Area Styles */
355
- .content-container {
356
- min-height: 90vh;
357
- padding: 20px;
358
- }
359
-
360
- .content-area {
361
- width: 100%;
362
- height: calc(100vh - 80px);
363
- background: rgba(255, 255, 255, 0.05);
364
- border-radius: 8px;
365
- box-shadow: 0 1px 3px rgba(0,0,0,0.3), 0 1px 2px rgba(0,0,0,0.2);
366
- overflow: hidden;
367
- border: 1px solid #374151;
368
- }
369
-
370
- .content-iframe {
371
- width: 100%;
372
- height: 100%;
373
- border: none;
374
- background: rgba(255, 255, 255, 0.05);
375
- display: block;
376
- box-sizing: border-box;
377
- }
378
-
379
- /* Refresh Button Styles */
380
- .refresh-btn {
381
- font-family: helvetica neue;
382
- font-weight: bold;
383
- position: fixed;
384
- top: 0.5rem;
385
- left: 0.5rem;
386
- background: #212529;
387
- color: #fff;
388
- border: 0px;
389
- border-radius: 6px;
390
- padding: 12px 20px;
391
- font-size: 14px;
392
- cursor: pointer;
393
- backdrop-filter: blur(10px);
394
- transition: all 0.2s ease;
395
- opacity: 1;
396
- z-index: 1000;
397
- white-space: nowrap;
398
- width: auto;
399
- max-width: fit-content;
400
- }
401
-
402
- .refresh-btn:hover {
403
- background: #424649;
404
- border-color: #6b7280;
405
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
406
- }
407
-
408
- /* Flash Messages */
409
- .flash-messages {
410
- position: fixed;
411
- top: 25px;
412
- left: 50%;
413
- transform: translateX(-50%);
414
- z-index: 1001;
415
- }
416
-
417
- .flash-message {
418
- background: rgba(0, 57, 150, 0.4);
419
- color: #fff;
420
- padding: 12px 20px;
421
- border-radius: 6px;
422
- margin-bottom: 10px;
423
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3), 0 1px 2px rgba(0, 0, 0, 0.2);
424
- font-weight: 500;
425
- backdrop-filter: blur(10px);
426
- text-align: center;
427
- }
428
-
429
- /* Loading Animation */
430
- .loading {
431
- display: none;
432
- position: absolute;
433
- top: 50%;
434
- left: 50%;
435
- transform: translate(-50%, -50%);
436
- }
437
-
438
- .loading.active {
439
- display: block;
440
- }
441
-
442
- .spinner {
443
- width: 40px;
444
- height: 40px;
445
- border: 3px solid #4a5568;
446
- border-top: 3px solid #f3f3f3;
447
- border-radius: 50%;
448
- animation: spin 1s linear infinite;
449
- }
450
-
451
- @keyframes spin {
452
- 0% { transform: rotate(0deg); }
453
- 100% { transform: rotate(360deg); }
454
- }
455
-
456
- /* Responsive Design */
457
- @media (max-width: 768px) {
458
- .upload-area {
459
- height: 250px;
460
- margin: 0 1rem;
461
- padding: 0 1rem;
462
- max-width: calc(100vw - 2rem);
463
- }
464
-
465
- .upload-text {
466
- font-size: 16px;
467
- text-align: center;
468
- }
469
-
470
- .upload-subtext {
471
- font-size: 13px;
472
- text-align: center;
473
- }
474
-
475
- .upload-container {
476
- padding: 0 1rem;
477
- }
478
-
479
- .refresh-btn {
480
- top: 10px;
481
- left: 10px;
482
- padding: 8px 12px;
483
- font-size: 11px;
484
- white-space: nowrap;
485
- width: auto;
486
- max-width: fit-content;
487
- }
488
- }
489
-
490
- @media (max-width: 480px) {
491
- .upload-area {
492
- height: 220px;
493
- margin: 0 0.5rem;
494
- padding: 0 0.5rem;
495
- max-width: calc(100vw - 1rem);
496
- }
497
 
498
- .upload-text {
499
- font-size: 14px;
500
- }
 
 
 
501
 
502
- .upload-subtext {
503
- font-size: 12px;
504
- }
505
-
506
- .upload-icon {
507
- font-size: 36px;
508
- margin-bottom: 15px;
509
- }
 
 
510
 
511
- .upload-container {
512
- padding: 0 0.5rem;
513
- }
514
- }
515
- </style>
516
- </head>
517
- <body>
518
- <!-- Flash Messages -->
519
- {% with messages = get_flashed_messages() %}
520
- {% if messages %}
521
- <div class="flash-messages">
522
- {% for message in messages %}
523
- <div class="flash-message">{{ message }}</div>
524
- {% endfor %}
525
- </div>
526
- {% endif %}
527
- {% endwith %}
528
-
529
- <!-- Refresh Button (only visible after upload) -->
530
- {% if session.uploaded_file %}
531
- <button class="refresh-btn" onclick="refreshSession()">
532
- Start over
533
- </button>
534
- {% endif %}
535
-
536
- {% if not session.uploaded_file %}
537
- <!-- Upload Interface -->
538
- <h2 style="text-align: center; margin-top: 0.25rem;">Rag Document Viewer Demo</h2>
539
- <div class="upload-container">
540
- <form id="uploadForm" method="POST" action="/upload" enctype="multipart/form-data">
541
- <div class="upload-area" id="uploadArea">
542
- <div class="upload-icon">๐Ÿ“‚</div>
543
- <div class="upload-text">Drop your file here or click to browse</div>
544
- <div class="upload-subtext">Supports: PDFs, Office Documents, OpenOffice Documents <br>(Max: 16MB)</div>
545
- <input type="file" name="file" class="file-input" id="fileInput" accept=".txt,.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.odt,.odp,.ods">
546
- <div class="loading" id="loading">
547
- <div class="spinner"></div>
548
- </div>
549
- </div>
550
- </form>
551
- </div>
552
- {% else %}
553
- <!-- Content Interface -->
554
- <h2 style="text-align: center; margin-top: 0.25rem;">Rag Document Viewer Demo</h2>
555
- <div class="content-container">
556
- <div class="content-area">
557
- <div class="content-iframe">
558
- <iframe src="{{ url_for('load', filename=session.uploaded_file) }}"
559
- style="width: 100%; height: 100%; border: none; display: block;">
560
- </iframe>
561
- </div>
562
- </div>
563
- </div>
564
- {% endif %}
565
-
566
- <script>
567
- // File upload handling
568
- const uploadArea = document.getElementById('uploadArea');
569
- const fileInput = document.getElementById('fileInput');
570
- const uploadForm = document.getElementById('uploadForm');
571
- const loading = document.getElementById('loading');
572
-
573
- if (uploadArea) {
574
- // Click to browse
575
- uploadArea.addEventListener('click', () => {
576
- fileInput.click();
577
- });
578
-
579
- // Drag and drop
580
- uploadArea.addEventListener('dragover', (e) => {
581
- e.preventDefault();
582
- uploadArea.classList.add('dragover');
583
- });
584
-
585
- uploadArea.addEventListener('dragleave', () => {
586
- uploadArea.classList.remove('dragover');
587
- });
588
-
589
- uploadArea.addEventListener('drop', (e) => {
590
- e.preventDefault();
591
- uploadArea.classList.remove('dragover');
592
-
593
- const files = e.dataTransfer.files;
594
- if (files.length > 0) {
595
- const file = files[0];
596
- const maxSize = 16 * 1024 * 1024; // 16MB
597
-
598
- if (file.size > maxSize) {
599
- // Redirect to file size error route instead of alert
600
- window.location.href = '/file_size_error';
601
- return;
602
- }
603
-
604
- fileInput.files = files;
605
- submitForm();
606
- }
607
- });
608
-
609
- // File input change
610
- fileInput.addEventListener('change', () => {
611
- if (fileInput.files.length > 0) {
612
- const file = fileInput.files[0];
613
- const maxSize = 16 * 1024 * 1024; // 16MB
614
-
615
- if (file.size > maxSize) {
616
- // Redirect to file size error route instead of alert
617
- fileInput.value = ''; // Clear the file input
618
- window.location.href = '/file_size_error';
619
- return;
620
- }
621
-
622
- submitForm();
623
- }
624
- });
625
-
626
- function submitForm() {
627
- loading.classList.add('active');
628
- uploadForm.submit();
629
- }
630
- }
631
-
632
- // Refresh session function
633
- function refreshSession() {
634
- window.location.href = '/refresh';
635
- }
636
-
637
- // Auto-hide flash messages after 3 seconds
638
- setTimeout(() => {
639
- const flashMessages = document.querySelector('.flash-messages');
640
- if (flashMessages) {
641
- flashMessages.style.opacity = '0';
642
- flashMessages.style.transition = 'opacity 0.5s ease';
643
- setTimeout(() => {
644
- flashMessages.style.display = 'none';
645
- }, 500);
646
- }
647
- }, 5000);
648
- </script>
649
- </body>
650
- </html>
651
- '''
652
 
653
- if __name__ == '__main__':
654
- app.run(debug=True)
 
 
 
 
 
 
 
 
 
 
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
 
10
  # Import with proper error handling
11
  try:
 
14
  print(f"Warning: Could not import RAG_DV: {e}")
15
  RAG_DV = None
16
 
17
+ # Configure logging
18
+ logging.basicConfig(level=logging.INFO)
19
+ logger = logging.getLogger(__name__)
20
 
21
+ # Setup uploads directory
22
  if os.getenv("SPACE_ID"):
23
  uploads_dir = Path(tempfile.gettempdir()) / "uploads"
24
  else:
 
26
 
27
  uploads_dir.mkdir(exist_ok=True)
28
 
29
+ # Configuration
30
+ MAX_FILE_SIZE = 16 * 1024 # 16MB
 
 
 
 
 
 
 
 
 
31
  ALLOWED_EXTENSIONS = {'txt', 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'odt', 'odp', 'ods'}
32
 
33
  def allowed_file(filename):
34
  return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
35
 
36
+ def process_uploaded_file(file):
37
+ """Process uploaded file and return status message and HTML content"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  try:
39
  # Check if RAG_DV is available
40
  if RAG_DV is None:
41
+ return (
42
+ "โŒ RAG Document Viewer is not available. Please check the installation.",
43
+ None,
44
+ gr.update(visible=True), # upload interface
45
+ gr.update(visible=False), # content interface
46
+ gr.update(visible=False) # refresh button
47
+ )
48
+
49
+ # Validate file
50
+ if file is None:
51
+ return (
52
+ "โŒ No file selected",
53
+ None,
54
+ gr.update(visible=True),
55
+ gr.update(visible=False),
56
+ gr.update(visible=False)
57
+ )
58
 
59
+ # Check file size
60
+ file_size = os.path.getsize(file.name)
61
+ if file_size > MAX_FILE_SIZE:
62
+ return (
63
+ "โŒ File is too large. Maximum size is 16MB.",
64
+ None,
65
+ gr.update(visible=True),
66
+ gr.update(visible=False),
67
+ gr.update(visible=False)
68
+ )
69
 
70
+ # Get original filename
71
+ original_filename = Path(file.name).name
 
72
 
73
+ if not allowed_file(original_filename):
74
+ return (
75
+ "โŒ Invalid file type. Please upload a supported document.",
76
+ None,
77
+ gr.update(visible=True),
78
+ gr.update(visible=False),
79
+ gr.update(visible=False)
80
+ )
81
 
82
+ # Generate unique filename
83
+ filename = secure_filename(original_filename)
84
  if not filename:
85
+ return (
86
+ "โŒ Invalid filename",
87
+ None,
88
+ gr.update(visible=True),
89
+ gr.update(visible=False),
90
+ gr.update(visible=False)
91
+ )
92
 
93
  unique_filename = f"{uuid.uuid4()}_{filename}"
94
 
95
  # Create directory structure
96
  dir_name = Path(str(unique_filename).replace(Path(unique_filename).suffix, ""))
97
+ dir_path = uploads_dir / dir_name
98
 
99
  try:
100
  dir_path.mkdir(parents=True, exist_ok=True)
101
  except OSError as e:
102
  logger.error(f"Failed to create directory {dir_path}: {e}")
103
+ return (
104
+ "โŒ Failed to create upload directory",
105
+ None,
106
+ gr.update(visible=True),
107
+ gr.update(visible=False),
108
+ gr.update(visible=False)
109
+ )
110
 
111
  file_path = dir_path / unique_filename
112
 
113
+ # Copy file to new location
114
  try:
115
+ import shutil
116
+ shutil.copy2(file.name, str(file_path))
117
  except Exception as e:
118
  logger.error(f"Failed to save file {file_path}: {e}")
119
+ return (
120
+ "โŒ Failed to save uploaded file",
121
+ None,
122
+ gr.update(visible=True),
123
+ gr.update(visible=False),
124
+ gr.update(visible=False)
125
+ )
126
 
127
  # Verify file was saved
128
  if not file_path.exists():
129
+ return (
130
+ "โŒ File upload failed - file not saved",
131
+ None,
132
+ gr.update(visible=True),
133
+ gr.update(visible=False),
134
+ gr.update(visible=False)
135
+ )
136
 
137
  # Process with RAG_DV
138
  rag_output_path = file_path.parent / "rag_dv"
 
150
  except Exception as cleanup_error:
151
  logger.error(f"Failed to cleanup after RAG_DV error: {cleanup_error}")
152
 
153
+ return (
154
+ "โŒ Failed to process document. Please try again or use a different file.",
155
+ None,
156
+ gr.update(visible=True),
157
+ gr.update(visible=False),
158
+ gr.update(visible=False)
159
+ )
160
 
161
  # Verify RAG processing created the expected output
162
  index_file = rag_output_path / "index.html"
163
  if not index_file.exists():
164
+ return (
165
+ "โŒ Document processing incomplete. Please try again.",
166
+ None,
167
+ gr.update(visible=True),
168
+ gr.update(visible=False),
169
+ gr.update(visible=False)
170
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
+ # Read the HTML content
173
  try:
174
  with open(index_file, 'r', encoding='utf-8') as f:
175
+ html_content = f.read()
176
  except Exception as e:
177
  logger.error(f"Failed to read index file {index_file}: {e}")
178
+ return (
179
+ "โŒ Failed to load document content",
180
+ None,
181
+ gr.update(visible=True),
182
+ gr.update(visible=False),
183
+ gr.update(visible=False)
184
+ )
185
 
186
+ return (
187
+ f"โœ… File '{original_filename}' successfully uploaded and processed!",
188
+ html_content,
189
+ gr.update(visible=False), # hide upload interface
190
+ gr.update(visible=True), # show content interface
191
+ gr.update(visible=True) # show refresh button
192
+ )
193
 
194
  except Exception as e:
195
+ logger.error(f"Unexpected error in process_uploaded_file: {e}")
196
  logger.error(f"Traceback: {traceback.format_exc()}")
197
+ return (
198
+ "โŒ Upload failed due to an unexpected error",
199
+ None,
200
+ gr.update(visible=True),
201
+ gr.update(visible=False),
202
+ gr.update(visible=False)
203
+ )
204
+
205
+ def refresh_session():
206
+ """Reset the interface to initial state"""
207
+ return (
208
+ "๐Ÿ”„ Session refreshed. You can upload a new file.",
209
+ None,
210
+ gr.update(visible=True), # show upload interface
211
+ gr.update(visible=False), # hide content interface
212
+ gr.update(visible=False) # hide refresh button
213
+ )
214
+
215
+ def create_app():
216
+ """Create the Gradio application"""
217
+
218
+ # Custom CSS to match the original design
219
+ custom_css = """
220
+ .gradio-container {
221
+ background: linear-gradient(135deg, hsla(0, 0%, 0%, 1) 0%, hsla(0, 0%, 11%, 1) 100%) !important;
222
+ min-height: 100vh;
223
+ color: #f3f3f3 !important;
224
+ }
225
+
226
+ .upload-container {
227
+ background: rgba(255, 255, 255, 0.05) !important;
228
+ border: 2px dashed #4a5568 !important;
229
+ border-radius: 8px !important;
230
+ padding: 2rem !important;
231
+ text-align: center !important;
232
+ transition: all 0.2s ease !important;
233
+ }
234
+
235
+ .upload-container:hover {
236
+ border-color: #6b7280 !important;
237
+ background: rgba(255, 255, 255, 0.08) !important;
238
+ }
239
+
240
+ .content-frame {
241
+ background: rgba(255, 255, 255, 0.05) !important;
242
+ border-radius: 8px !important;
243
+ border: 1px solid #374151 !important;
244
+ height: 80vh !important;
245
+ overflow: auto !important;
246
+ }
247
+
248
+ .status-message {
249
+ padding: 12px 20px !important;
250
+ border-radius: 6px !important;
251
+ margin: 10px 0 !important;
252
+ font-weight: 500 !important;
253
+ text-align: center !important;
254
+ }
255
+
256
+ .refresh-button {
257
+ background: #212529 !important;
258
+ color: #fff !important;
259
+ border: none !important;
260
+ border-radius: 6px !important;
261
+ padding: 12px 20px !important;
262
+ font-weight: bold !important;
263
+ }
264
+
265
+ .refresh-button:hover {
266
+ background: #424649 !important;
267
+ }
268
+ """
269
+
270
+ with gr.Blocks(css=custom_css, title="RAG Document Viewer Demo") as app:
271
 
272
+ # State to store the HTML content
273
+ html_content_state = gr.State(None)
 
274
 
275
+ # Header
276
+ gr.Markdown("# RAG Document Viewer Demo", elem_classes=["center"])
 
 
 
277
 
278
+ # Status message area
279
+ status_msg = gr.Markdown("", visible=False)
280
 
281
+ # Upload Interface
282
+ with gr.Column(visible=True) as upload_interface:
283
+ gr.Markdown("""
284
+ ### Upload Your Document
285
+ Drop your file here or click to browse
286
+ **Supports:** PDFs, Office Documents, OpenOffice Documents
287
+ **Max file size:** 16MB
288
+ """, elem_classes=["upload-container"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
 
290
+ file_input = gr.File(
291
+ label="Select File",
292
+ file_types=[".txt", ".pdf", ".doc", ".docx", ".ppt", ".pptx",
293
+ ".xls", ".xlsx", ".odt", ".odp", ".ods"],
294
+ elem_classes=["upload-area"]
295
+ )
296
 
297
+ upload_btn = gr.Button("Upload and Process", variant="primary")
298
+
299
+ # Content Interface
300
+ with gr.Column(visible=False) as content_interface:
301
+ with gr.Row():
302
+ refresh_btn = gr.Button(
303
+ "๐Ÿ”„ Start Over",
304
+ variant="secondary",
305
+ elem_classes=["refresh-button"]
306
+ )
307
 
308
+ # HTML content display
309
+ html_display = gr.HTML(
310
+ value="",
311
+ elem_classes=["content-frame"]
312
+ )
313
+
314
+ # Refresh button (separate for better control)
315
+ refresh_btn_separate = gr.Button(
316
+ "๐Ÿ”„ Start Over",
317
+ visible=False,
318
+ variant="secondary",
319
+ elem_classes=["refresh-button"]
320
+ )
321
+
322
+ # Event handlers
323
+ upload_btn.click(
324
+ fn=process_uploaded_file,
325
+ inputs=[file_input],
326
+ outputs=[
327
+ status_msg,
328
+ html_display,
329
+ upload_interface,
330
+ content_interface,
331
+ refresh_btn_separate
332
+ ]
333
+ ).then(
334
+ fn=lambda msg: gr.update(visible=bool(msg)),
335
+ inputs=[status_msg],
336
+ outputs=[status_msg]
337
+ )
338
+
339
+ # File input auto-upload (when file is selected)
340
+ file_input.change(
341
+ fn=process_uploaded_file,
342
+ inputs=[file_input],
343
+ outputs=[
344
+ status_msg,
345
+ html_display,
346
+ upload_interface,
347
+ content_interface,
348
+ refresh_btn_separate
349
+ ]
350
+ ).then(
351
+ fn=lambda msg: gr.update(visible=bool(msg)),
352
+ inputs=[status_msg],
353
+ outputs=[status_msg]
354
+ )
355
+
356
+ # Refresh handlers
357
+ refresh_btn.click(
358
+ fn=refresh_session,
359
+ outputs=[
360
+ status_msg,
361
+ html_display,
362
+ upload_interface,
363
+ content_interface,
364
+ refresh_btn_separate
365
+ ]
366
+ ).then(
367
+ fn=lambda msg: gr.update(visible=bool(msg)),
368
+ inputs=[status_msg],
369
+ outputs=[status_msg]
370
+ )
371
+
372
+ refresh_btn_separate.click(
373
+ fn=refresh_session,
374
+ outputs=[
375
+ status_msg,
376
+ html_display,
377
+ upload_interface,
378
+ content_interface,
379
+ refresh_btn_separate
380
+ ]
381
+ ).then(
382
+ fn=lambda msg: gr.update(visible=bool(msg)),
383
+ inputs=[status_msg],
384
+ outputs=[status_msg]
385
+ )
386
+
387
+ return app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
 
389
+ # Create and launch the app
390
+ if __name__ == "__main__":
391
+ app = create_app()
392
+
393
+ # Launch configuration
394
+ if os.getenv("SPACE_ID"):
395
+ # Running on Hugging Face Spaces
396
+ app.launch(server_name="0.0.0.0", server_port=7860)
397
+ else:
398
+ # Local development
399
+ app.launch(debug=True)