donotthink commited on
Commit
a0f99e4
·
verified ·
1 Parent(s): c2a982c

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +41 -13
app.py CHANGED
@@ -1,37 +1,50 @@
1
  import os
2
  import shutil
3
  import subprocess
 
4
  from pathlib import Path
5
 
6
  # ---- 自动拉取 Xet 指针文件(HF 用 Xet 管理大图片,构建时不会自动 materialize)----
7
  def _materialize_xet():
 
8
  repo_id = "donotthink/meme"
9
  base_url = f"https://huggingface.co/spaces/{repo_id}/resolve/main"
10
  exts = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp")
11
  count = 0
 
12
  for root, _dirs, files in os.walk("meme_generator"):
13
  for fname in files:
14
  if not fname.lower().endswith(exts):
15
  continue
16
  fpath = os.path.join(root, fname)
17
  try:
18
- if os.path.getsize(fpath) > 1024:
 
19
  continue
20
  with open(fpath, "r", errors="ignore") as f:
21
- head = f.read(64)
22
- if not head.startswith("xet"):
23
  continue
24
  rel = os.path.relpath(fpath, ".").replace(os.sep, "/")
25
  url = f"{base_url}/{rel}"
26
- subprocess.run(
27
- ["curl", "-fsSL", "-o", fpath, url],
28
- capture_output=True, timeout=30,
29
- )
30
- count += 1
31
- except Exception:
32
- pass
33
- if count:
34
- print(f"[xet] materialized {count} files")
 
 
 
 
 
 
 
 
 
35
 
36
  _materialize_xet()
37
 
@@ -115,7 +128,22 @@ def _generate(meme_key, *args):
115
  meme = _meme_map[meme_key]
116
  try:
117
  result = meme(images=images, texts=texts)
118
- return result.getvalue(), "✅ 生成成功!右键图片可保存"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  except MemeGeneratorException as e:
120
  return None, f"❌ {e}"
121
  except Exception as e:
 
1
  import os
2
  import shutil
3
  import subprocess
4
+ import urllib.request
5
  from pathlib import Path
6
 
7
  # ---- 自动拉取 Xet 指针文件(HF 用 Xet 管理大图片,构建时不会自动 materialize)----
8
  def _materialize_xet():
9
+ """检测并下载 Xet 指针文件,替换为真实图片。"""
10
  repo_id = "donotthink/meme"
11
  base_url = f"https://huggingface.co/spaces/{repo_id}/resolve/main"
12
  exts = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp")
13
  count = 0
14
+ failures = 0
15
  for root, _dirs, files in os.walk("meme_generator"):
16
  for fname in files:
17
  if not fname.lower().endswith(exts):
18
  continue
19
  fpath = os.path.join(root, fname)
20
  try:
21
+ # Xet 指针文件通常 < 1KB,内容以 "xet" 开头
22
+ if os.path.getsize(fpath) > 2048:
23
  continue
24
  with open(fpath, "r", errors="ignore") as f:
25
+ head = f.read(128)
26
+ if not head.lstrip().lower().startswith("xet"):
27
  continue
28
  rel = os.path.relpath(fpath, ".").replace(os.sep, "/")
29
  url = f"{base_url}/{rel}"
30
+ # 用 urllib 下载真实文件(HF resolve 会自动返回实际内容)
31
+ for attempt in range(3):
32
+ try:
33
+ req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
34
+ with urllib.request.urlopen(req, timeout=60) as resp:
35
+ data = resp.read()
36
+ if data and not data[:8].startswith(b"version"):
37
+ with open(fpath, "wb") as f:
38
+ f.write(data)
39
+ count += 1
40
+ break
41
+ except Exception:
42
+ if attempt == 2:
43
+ raise
44
+ except Exception as e:
45
+ failures += 1
46
+ print(f"[xet] materialized {count} files, {failures} failures")
47
+ return count
48
 
49
  _materialize_xet()
50
 
 
128
  meme = _meme_map[meme_key]
129
  try:
130
  result = meme(images=images, texts=texts)
131
+ data = result.getvalue()
132
+
133
+ # Gradio 6.x Image 组件不接受 bytes,需保存为临时文件返回路径
134
+ import io
135
+ import tempfile
136
+ from PIL import Image as PILImage
137
+
138
+ img = PILImage.open(io.BytesIO(data))
139
+ fmt = (img.format or "PNG").upper()
140
+ if fmt == "JPEG":
141
+ fmt = "JPG"
142
+ suffix = f".{fmt.lower()}"
143
+ fd, tmp_path = tempfile.mkstemp(suffix=suffix)
144
+ os.close(fd)
145
+ img.save(tmp_path, format=fmt)
146
+ return tmp_path, "✅ 生成成功!右键图片可保存"
147
  except MemeGeneratorException as e:
148
  return None, f"❌ {e}"
149
  except Exception as e: