import os import re import sys import threading from pathlib import Path import gradio as gr from flask import Flask, abort, send_from_directory def read_markdown(filepath): with open(filepath, 'r') as file: lines = file.readlines() start_index = None end_index = None for i, line in enumerate(lines): if line.strip() == '---': if start_index is None: start_index = i else: end_index = i break if end_index is None: return ''.join(lines) # If no end delimiter found, return entire content else: return ''.join(lines[end_index + 1:]) # Return content after end delimiter local_path = Path(sys.path[0]) filepath = local_path / "README.md" markdown_content = read_markdown(filepath) # Debug: Print the markdown content to check if it includes the image syntax print("Markdown Content:") print(markdown_content) app = Flask(__name__) @app.route('/assets/') def serve_assets(filename): # Safeguard against path traversal attacks and invalid paths safe_path = os.path.normpath(filename) if safe_path.startswith("..") or os.path.isabs(safe_path): print(f"Invalid path: {filename}") abort(400) # Bad request for invalid paths asset_path = local_path / 'assets' / safe_path if not asset_path.is_file(): print(f"File not found: {asset_path}") abort(404) # File not found try: print("ja") return send_from_directory(local_path / 'assets', safe_path) except Exception as e: print(f"Error serving file: {e}") abort(403) # Forbidden def run_flask(): app.run(port=5001, host='0.0.0.0') # Ensure the server is accessible flask_thread = threading.Thread(target=run_flask) flask_thread.start() # Update the image paths in the markdown to use the Flask server URL markdown_content = re.sub(r'assets/([^)\s]+)', r'http://127.0.0.1:5001/assets/\1', markdown_content) with gr.Blocks() as demo: gr.Markdown(markdown_content) demo.launch()