awacke1 commited on
Commit
3cb3215
·
verified ·
1 Parent(s): a6e4388

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -21
app.py CHANGED
@@ -44,29 +44,16 @@ FONT_DIR.mkdir(exist_ok=True)
44
  # --- Font & Emoji Handling ---
45
 
46
  def download_and_register_fonts():
47
- """Downloads default fonts if needed, then finds and registers all .ttf files."""
48
  print("--- Font Registration Process Starting ---")
49
- fonts_to_download = {
50
- "DejaVuSans.ttf": "https://github.com/dejavu-fonts/dejavu-fonts/blob/main/ttf/DejaVuSans.ttf?raw=true",
51
- "NotoColorEmoji.ttf": "https://github.com/googlefonts/noto-emoji/blob/main/fonts/NotoColorEmoji.ttf?raw=true"
52
- }
53
- for filename, url in fonts_to_download.items():
54
- font_path = FONT_DIR / filename
55
- if not font_path.exists():
56
- print(f"Downloading {filename}...")
57
- try:
58
- r = requests.get(url, allow_redirects=True, timeout=20)
59
- r.raise_for_status()
60
- with open(font_path, "wb") as f: f.write(r.content)
61
- print(f"{filename} downloaded.")
62
- except Exception as e:
63
- print(f"Failed to download {filename}: {e}")
64
-
65
  font_names = []
66
  print(f"Scanning for fonts in: {FONT_DIR.absolute()}")
67
  font_files = list(FONT_DIR.glob("*.ttf"))
68
  print(f"Found {len(font_files)} .ttf files: {[f.name for f in font_files]}")
69
 
 
 
 
70
  for font_path in font_files:
71
  try:
72
  font_name = font_path.stem
@@ -79,7 +66,9 @@ def download_and_register_fonts():
79
  pdfmetrics.registerFont(TTFont(f"{font_name}-BoldItalic", str(font_path)))
80
  pdfmetrics.registerFontFamily(font_name, normal=font_name, bold=f"{font_name}-Bold", italic=f"{font_name}-Italic", boldItalic=f"{font_name}-BoldItalic")
81
 
82
- if "emoji" not in font_name.lower():
 
 
83
  font_names.append(font_name)
84
  except Exception as e:
85
  print(f"Could not register font {font_path.name}: {e}")
@@ -89,12 +78,15 @@ def download_and_register_fonts():
89
 
90
  def apply_emoji_font(text: str) -> str:
91
  """Wraps emoji characters in a <font> tag to use the dedicated emoji font."""
 
 
 
92
  emoji_pattern = re.compile(f"([{re.escape(''.join(map(chr, range(0x1f600, 0x1f650))))}"
93
  f"{re.escape(''.join(map(chr, range(0x1f300, 0x1f5ff))))}"
94
  f"{re.escape(''.join(map(chr, range(0x1f900, 0x1f9ff))))}"
95
  f"{re.escape(''.join(map(chr, range(0x2600, 0x26ff))))}"
96
  f"{re.escape(''.join(map(chr, range(0x2700, 0x27bf))))}]+)")
97
- return emoji_pattern.sub(fr'<font name="{EMOJI_FONT_NAME}">\1</font>', text)
98
 
99
 
100
  # --- PDF Generation & Handling ---
@@ -226,10 +218,23 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Advanced PDF Generator") as demo:
226
  """Function to run on app load to generate a sample PDF."""
227
  print("Running initial demo generation...")
228
  # Create a dummy file object for Gradio
229
- with open(CWD / "sample.md", "rb") as f:
 
 
 
 
230
  sample_bytes = f.read()
231
 
232
- demo_files = [gr.processing_utils.SavedFile(name=str(CWD / "sample.md"), data=sample_bytes, is_file=True)]
 
 
 
 
 
 
 
 
 
233
  previews, logs, files = generate_pdfs_api(demo_files, ["A4 Portrait"], [AVAILABLE_FONTS[0]] if AVAILABLE_FONTS else [], 1)
234
  return previews, logs, files
235
 
 
44
  # --- Font & Emoji Handling ---
45
 
46
  def download_and_register_fonts():
47
+ """Finds and registers all .ttf files from the local 'fonts' directory."""
48
  print("--- Font Registration Process Starting ---")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  font_names = []
50
  print(f"Scanning for fonts in: {FONT_DIR.absolute()}")
51
  font_files = list(FONT_DIR.glob("*.ttf"))
52
  print(f"Found {len(font_files)} .ttf files: {[f.name for f in font_files]}")
53
 
54
+ if not font_files:
55
+ print("WARNING: No .ttf files found in the 'fonts' directory. Please add font files to use them in the application.")
56
+
57
  for font_path in font_files:
58
  try:
59
  font_name = font_path.stem
 
66
  pdfmetrics.registerFont(TTFont(f"{font_name}-BoldItalic", str(font_path)))
67
  pdfmetrics.registerFontFamily(font_name, normal=font_name, bold=f"{font_name}-Bold", italic=f"{font_name}-Italic", boldItalic=f"{font_name}-BoldItalic")
68
 
69
+ # Exclude specific emoji fonts from the main selection list as they are handled automatically.
70
+ # We use a more general check to catch variants like NotoEmoji-Bold etc.
71
+ if "notoemoji" not in font_name.lower():
72
  font_names.append(font_name)
73
  except Exception as e:
74
  print(f"Could not register font {font_path.name}: {e}")
 
78
 
79
  def apply_emoji_font(text: str) -> str:
80
  """Wraps emoji characters in a <font> tag to use the dedicated emoji font."""
81
+ # Assuming 'NotoColorEmoji-Regular' is the intended font for color emojis.
82
+ # The font name here must match the one registered from the filename.
83
+ emoji_font_to_use = "NotoColorEmoji-Regular"
84
  emoji_pattern = re.compile(f"([{re.escape(''.join(map(chr, range(0x1f600, 0x1f650))))}"
85
  f"{re.escape(''.join(map(chr, range(0x1f300, 0x1f5ff))))}"
86
  f"{re.escape(''.join(map(chr, range(0x1f900, 0x1f9ff))))}"
87
  f"{re.escape(''.join(map(chr, range(0x2600, 0x26ff))))}"
88
  f"{re.escape(''.join(map(chr, range(0x2700, 0x27bf))))}]+)")
89
+ return emoji_pattern.sub(fr'<font name="{emoji_font_to_use}">\1</font>', text)
90
 
91
 
92
  # --- PDF Generation & Handling ---
 
218
  """Function to run on app load to generate a sample PDF."""
219
  print("Running initial demo generation...")
220
  # Create a dummy file object for Gradio
221
+ sample_md_path = CWD / "sample.md"
222
+ if not sample_md_path.exists():
223
+ return [], "Sample.md not found.", []
224
+
225
+ with open(sample_md_path, "rb") as f:
226
  sample_bytes = f.read()
227
 
228
+ # This part is tricky with Gradio's file handling on load.
229
+ # For simplicity, we'll pass the path and have the API function handle it.
230
+ # A more robust solution might involve writing to a temp file.
231
+ # This is a conceptual fix for the demo.
232
+ class TempFile:
233
+ def __init__(self, name):
234
+ self.name = name
235
+
236
+ demo_files = [TempFile(name=str(sample_md_path))]
237
+
238
  previews, logs, files = generate_pdfs_api(demo_files, ["A4 Portrait"], [AVAILABLE_FONTS[0]] if AVAILABLE_FONTS else [], 1)
239
  return previews, logs, files
240