hagras commited on
Commit
fb45bed
·
verified ·
1 Parent(s): 8ded10f

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +77 -3
server.py CHANGED
@@ -70,6 +70,55 @@ def _json_response(success: bool = True, message: str = "", data: Dict[Any, Any]
70
  })
71
 
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  # --------------------------------------------------------------------------- #
74
  # Template #
75
  # --------------------------------------------------------------------------- #
@@ -748,8 +797,20 @@ def load(request: Request, filename: str):
748
  raise HTTPException(status_code=404, detail="Document index not found.")
749
 
750
  logger.info(f"Loading document: {filename}")
 
 
 
 
 
 
 
751
  with open(idx_file, "r", encoding="utf-8") as f:
752
  content = f.read()
 
 
 
 
 
753
  return HTMLResponse(content)
754
 
755
 
@@ -764,22 +825,35 @@ def load_assets(request: Request, asset_path: str):
764
  logger.info(f"Uploaded file: {request.session.get('uploaded_file')}")
765
 
766
  uploaded_file = request.session["uploaded_file"]
767
- base_dir = UPLOADS_DIR / Path(uploaded_file).stem / "rag_dv" / "assets"
 
768
 
769
  # Construct the full file path
770
  file_path = base_dir / asset_path
771
 
 
772
  logger.info(f"Looking for asset at: {file_path}")
773
  logger.info(f"Base directory exists: {base_dir.exists()}")
774
 
775
  if base_dir.exists():
776
  logger.info(f"Contents of assets dir: {list(base_dir.rglob('*'))}")
777
 
778
- if not file_path.exists():
779
  logger.error(f"Asset not found: {file_path}")
780
  raise HTTPException(status_code=404, detail=f"Asset not found: {asset_path}")
781
 
782
- return FileResponse(file_path)
 
 
 
 
 
 
 
 
 
 
 
783
 
784
 
785
  # ----------------------------- Error handling ------------------------------ #
 
70
  })
71
 
72
 
73
+ def _rewrite_html_urls(content: str, base_url: str, story_id: str) -> str:
74
+ """Rewrite relative URLs in HTML content to use absolute URLs"""
75
+ import re
76
+
77
+ logger.info(f"Rewriting URLs with base: {base_url}, story_id: {story_id}")
78
+
79
+ # Patterns to match various asset references
80
+ patterns = [
81
+ # src="assets/..." -> src="[base_url]/..."
82
+ (r'src="assets/', f'src="{base_url}/'),
83
+
84
+ # href="assets/..." -> href="[base_url]/..."
85
+ (r'href="assets/', f'href="{base_url}/'),
86
+
87
+ # CSS url(assets/...) -> url([base_url]/...)
88
+ (r'url\(assets/', f'url({base_url}/'),
89
+ (r'url\("assets/', f'url("{base_url}/'),
90
+ (r"url\('assets/", f"url('{base_url}/"),
91
+
92
+ # Background images and other asset references
93
+ (r'background-image:\s*url\(assets/', f'background-image: url({base_url}/'),
94
+ (r'background:\s*url\(assets/', f'background: url({base_url}/'),
95
+
96
+ # Script src
97
+ (r'<script[^>]*src="assets/', f'<script src="{base_url}/'),
98
+
99
+ # Link href (stylesheets, etc.)
100
+ (r'<link[^>]*href="assets/', f'<link href="{base_url}/'),
101
+ ]
102
+
103
+ # Apply all patterns
104
+ for pattern, replacement in patterns:
105
+ old_content = content
106
+ content = re.sub(pattern, replacement, content, flags=re.IGNORECASE)
107
+ if content != old_content:
108
+ logger.info(f"Applied pattern: {pattern}")
109
+
110
+ # Add base tag if not present
111
+ if '<base' not in content.lower():
112
+ base_tag = f'<base href="{base_url}/">'
113
+ if '<head>' in content.lower():
114
+ content = re.sub(r'<head>', f'<head>\n {base_tag}', content, flags=re.IGNORECASE)
115
+ else:
116
+ # If no head tag, add it
117
+ content = re.sub(r'<html[^>]*>', f'<html>\n<head>\n {base_tag}\n</head>', content, flags=re.IGNORECASE)
118
+
119
+ return content
120
+
121
+
122
  # --------------------------------------------------------------------------- #
123
  # Template #
124
  # --------------------------------------------------------------------------- #
 
797
  raise HTTPException(status_code=404, detail="Document index not found.")
798
 
799
  logger.info(f"Loading document: {filename}")
800
+
801
+ # Get the story_id (filename without extension and UUID prefix)
802
+ story_id = Path(filename).stem
803
+
804
+ # Construct base URL for assets
805
+ base_url = str(request.base_url).rstrip('/') + f"/load/assets"
806
+
807
  with open(idx_file, "r", encoding="utf-8") as f:
808
  content = f.read()
809
+
810
+ # Rewrite URLs to use absolute paths
811
+ content = _rewrite_html_urls(content, base_url, story_id)
812
+
813
+ logger.info(f"Document loaded with base URL: {base_url}")
814
  return HTMLResponse(content)
815
 
816
 
 
825
  logger.info(f"Uploaded file: {request.session.get('uploaded_file')}")
826
 
827
  uploaded_file = request.session["uploaded_file"]
828
+ story_id = Path(uploaded_file).stem # This is our story_id
829
+ base_dir = UPLOADS_DIR / story_id / "rag_dv" / "assets"
830
 
831
  # Construct the full file path
832
  file_path = base_dir / asset_path
833
 
834
+ logger.info(f"Story ID: {story_id}")
835
  logger.info(f"Looking for asset at: {file_path}")
836
  logger.info(f"Base directory exists: {base_dir.exists()}")
837
 
838
  if base_dir.exists():
839
  logger.info(f"Contents of assets dir: {list(base_dir.rglob('*'))}")
840
 
841
+ if not file_path.exists() or not file_path.is_file():
842
  logger.error(f"Asset not found: {file_path}")
843
  raise HTTPException(status_code=404, detail=f"Asset not found: {asset_path}")
844
 
845
+ # Set appropriate content type based on file extension
846
+ from mimetypes import guess_type
847
+ content_type, _ = guess_type(str(file_path))
848
+
849
+ return FileResponse(
850
+ file_path,
851
+ media_type=content_type,
852
+ headers={
853
+ "Cache-Control": "public, max-age=3600", # Cache for 1 hour
854
+ "X-Story-ID": story_id # Custom header for debugging
855
+ }
856
+ )
857
 
858
 
859
  # ----------------------------- Error handling ------------------------------ #