hagras commited on
Commit
1b2be00
ยท
verified ยท
1 Parent(s): 271e50a

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +114 -6
server.py CHANGED
@@ -6,6 +6,7 @@ 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:
@@ -30,9 +31,98 @@ uploads_dir.mkdir(exist_ok=True)
30
  MAX_FILE_SIZE = 16 * 1024 * 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:
@@ -72,7 +162,7 @@ def process_uploaded_file(file):
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),
@@ -169,6 +259,10 @@ def process_uploaded_file(file):
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:
@@ -183,6 +277,9 @@ def process_uploaded_file(file):
183
  gr.update(visible=False)
184
  )
185
 
 
 
 
186
  return (
187
  f"โœ… File '{original_filename}' successfully uploaded and processed!",
188
  html_content,
@@ -204,6 +301,10 @@ def process_uploaded_file(file):
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,
@@ -269,9 +370,6 @@ def create_app():
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
 
@@ -319,6 +417,7 @@ def create_app():
319
  elem_classes=["refresh-button"]
320
  )
321
 
 
322
  # Event handlers
323
  upload_btn.click(
324
  fn=process_uploaded_file,
@@ -393,7 +492,16 @@ if __name__ == "__main__":
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)
 
 
 
 
 
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:
 
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:
 
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),
 
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:
 
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,
 
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,
 
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
 
 
417
  elem_classes=["refresh-button"]
418
  )
419
 
420
+
421
  # Event handlers
422
  upload_btn.click(
423
  fn=process_uploaded_file,
 
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
+ )