feifeinoban commited on
Commit
e55329c
·
1 Parent(s): 3417d6b

Fix image path for Gradio rendering

Browse files
Files changed (1) hide show
  1. app.py +27 -12
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import gradio as gr
2
  import re
 
3
 
4
  def load_and_fix_markdown():
5
  with open("README.md", "r", encoding="utf-8") as f:
@@ -11,22 +12,36 @@ def load_and_fix_markdown():
11
  if len(parts) >= 3:
12
  content = parts[2].strip()
13
 
14
- # 修复所有图片路径 - 这是关键!
15
  def replace_path(match):
16
- path = match.group(1)
17
- # 如果是绝对URL,保留域名但简化路径
18
- if path.startswith("https://huggingface.co/spaces/"):
19
- return f'![](/assets/{path.split("assets/")[-1]})'
20
- # 如果是相对路径,转换为应用根路径
21
- elif "assets/" in path:
22
- return f'![](/assets/{path.split("assets/")[-1]})'
23
- return match.group(0)
24
-
25
- content = re.sub(r'!\[.*?\]\((.*?)\)', replace_path, content)
 
 
 
 
 
 
 
 
 
 
 
 
26
 
 
27
  return content
28
 
29
  with gr.Blocks() as demo:
30
  gr.Markdown(load_and_fix_markdown())
31
 
32
- demo.launch()
 
 
1
  import gradio as gr
2
  import re
3
+ import os
4
 
5
  def load_and_fix_markdown():
6
  with open("README.md", "r", encoding="utf-8") as f:
 
12
  if len(parts) >= 3:
13
  content = parts[2].strip()
14
 
15
+ # 修复所有图片路径
16
  def replace_path(match):
17
+ alt_text = match.group(1) or ""
18
+ path = match.group(2)
19
+
20
+ # 如果已经是完整URL,保持不变
21
+ if path.startswith(("http://", "https://")):
22
+ return f'![{alt_text}]({path})'
23
+
24
+ # 处理相对路径
25
+ clean_path = path.lstrip('./')
26
+
27
+ # 确保路径存在
28
+ if os.path.exists(clean_path):
29
+ return f'![{alt_text}](/file={clean_path})'
30
+ else:
31
+ # 如果文件不存在,尝试在assets目录中查找
32
+ filename = os.path.basename(clean_path)
33
+ assets_path = f"assets/{filename}"
34
+ if os.path.exists(assets_path):
35
+ return f'![{alt_text}](/file={assets_path})'
36
+ else:
37
+ # 文件不存在,返回原始路径(可能会有警告)
38
+ return f'![{alt_text}]({path})'
39
 
40
+ content = re.sub(r'!\[(.*?)\]\((.*?)\)', replace_path, content)
41
  return content
42
 
43
  with gr.Blocks() as demo:
44
  gr.Markdown(load_and_fix_markdown())
45
 
46
+ # 允许访问当前目录和可能的assets目录
47
+ demo.launch(allowed_paths=["./", "./assets"])