Nav3005 commited on
Commit
add2fed
·
verified ·
1 Parent(s): 429ccef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -44
app.py CHANGED
@@ -173,50 +173,70 @@ def get_audio_duration(audio_path):
173
  except Exception as e: raise Exception(f"Failed to get audio duration: {str(e)}")
174
 
175
  def create_reddit_card_with_text(template_path, hook_text, output_dir, config=REDDIT_CONFIG):
176
- try:
177
- template = Image.open(template_path).convert('RGBA')
178
- # WITH THIS:
179
- baked_dpi = template.info.get('dpi', (96, 96))
180
- dpi_x = baked_dpi[0] if isinstance(baked_dpi, tuple) else baked_dpi
181
- if dpi_x and dpi_x != 96:
182
- scale = dpi_x / 96
183
- new_w = int(template.width * scale)
184
- new_h = int(template.height * scale)
185
- template = template.resize((new_w, new_h), Image.LANCZOS)
186
- temp_w, temp_h = template.size
187
- box_w = int(temp_w * config['text_box_width_percent'])
188
- box_h = int(temp_h * config['text_box_height_percent'])
189
- script_dir = os.path.dirname(os.path.abspath(__file__))
190
- font_paths = [os.path.join(script_dir, 'fonts', config['font_file']), os.path.join(script_dir, config['font_file'])]
191
- best_font_size = config['font_size_max']
192
- best_wrapped_text = hook_text
193
- for font_size in range(config['font_size_max'], config['font_size_min'] - 1, -2):
194
- font = None
195
- for fp in font_paths:
196
- if os.path.exists(fp):
197
- try: font = ImageFont.truetype(fp, font_size); break
198
- except: pass
199
- if font is None: font = ImageFont.load_default()
200
- wrapped = textwrap.fill(hook_text, width=config['text_wrap_width'])
201
- draw = ImageDraw.Draw(template)
202
- bbox = draw.multiline_textbbox((0, 0), wrapped, font=font, spacing=config['line_spacing'])
203
- if (bbox[2]-bbox[0] <= box_w and bbox[3]-bbox[1] <= box_h):
204
- best_font_size = font_size; best_wrapped_text = wrapped; break
205
- font = None
206
- for fp in font_paths:
207
- if os.path.exists(fp):
208
- try: font = ImageFont.truetype(fp, best_font_size); break
209
- except: pass
210
- if font is None: font = ImageFont.load_default()
211
- draw = ImageDraw.Draw(template)
212
- bbox = draw.multiline_textbbox((0, 0), best_wrapped_text, font=font, spacing=config['line_spacing'])
213
- x = (temp_w - (bbox[2]-bbox[0])) / 2
214
- y = (temp_h - (bbox[3]-bbox[1])) / 2 + config['y_offset']
215
- draw.multiline_text((x, y), best_wrapped_text, fill=config['text_color'], font=font, spacing=config['line_spacing'], align='left')
216
- output_path = os.path.join(output_dir, 'reddit_card_composite.png')
217
- template.save(output_path, 'PNG')
218
- return output_path
219
- except Exception as e: raise Exception(f"Failed to create Reddit card: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  def validate_and_get_file(uploaded_file, url_string, file_type, temp_dir):
222
  has_upload = uploaded_file is not None
 
173
  except Exception as e: raise Exception(f"Failed to get audio duration: {str(e)}")
174
 
175
  def create_reddit_card_with_text(template_path, hook_text, output_dir, config=REDDIT_CONFIG):
176
+ try:
177
+ script_dir = os.path.dirname(os.path.abspath(__file__))
178
+ font_paths = [
179
+ os.path.join(script_dir, 'fonts', config['font_file']),
180
+ os.path.join(script_dir, config['font_file'])
181
+ ]
182
+ font_path = next((fp for fp in font_paths if os.path.exists(fp)), None)
183
+ if not font_path:
184
+ raise Exception(f"Font file not found: {config['font_file']}")
185
+
186
+ output_path = os.path.join(output_dir, 'reddit_card_composite.png')
187
+
188
+ # Wrap text manually
189
+ wrapped_text = textwrap.fill(hook_text, width=config['text_wrap_width'])
190
+ # FFmpeg drawtext uses \n for newlines
191
+ escaped_text = wrapped_text.replace("'", "\\'").replace('\n', '\n').replace(':', '\\:')
192
+
193
+ # Get template dimensions using ffprobe
194
+ cmd_probe = [
195
+ "ffprobe", "-v", "error", "-select_streams", "v:0",
196
+ "-show_entries", "stream=width,height",
197
+ "-of", "csv=s=x:p=0", template_path
198
+ ]
199
+ result = subprocess.run(cmd_probe, capture_output=True, text=True, check=True)
200
+ temp_w, temp_h = map(int, result.stdout.strip().split('x'))
201
+
202
+ # Calculate font size to fit the text box
203
+ box_w = int(temp_w * config['text_box_width_percent'])
204
+ box_h = int(temp_h * config['text_box_height_percent'])
205
+ font_size = config['font_size_max']
206
+
207
+ # Binary search for fitting font size
208
+ for fs in range(config['font_size_max'], config['font_size_min'] - 1, -2):
209
+ # Estimate: average char width ~ 0.6 * font_size, line height ~ 1.2 * font_size
210
+ lines = wrapped_text.split('\n')
211
+ max_line_len = max(len(l) for l in lines)
212
+ est_w = max_line_len * fs * 0.6
213
+ est_h = len(lines) * fs * 1.2
214
+ if est_w <= box_w and est_h <= box_h:
215
+ font_size = fs
216
+ break
217
+
218
+ # Build drawtext filter — x/y centers the text
219
+ drawtext_filter = (
220
+ f"drawtext=fontfile='{font_path}'"
221
+ f":text='{escaped_text}'"
222
+ f":fontcolor={config['text_color']}"
223
+ f":fontsize={font_size}"
224
+ f":line_spacing={config['line_spacing']}"
225
+ f":x=(w-text_w)/2"
226
+ f":y=(h-text_h)/2+{config['y_offset']}"
227
+ )
228
+
229
+ cmd = [
230
+ "ffmpeg", "-i", template_path,
231
+ "-vf", drawtext_filter,
232
+ "-frames:v", "1",
233
+ "-y", output_path
234
+ ]
235
+ subprocess.run(cmd, check=True, capture_output=True, text=True)
236
+ return output_path
237
+
238
+ except Exception as e:
239
+ raise Exception(f"Failed to create Reddit card: {str(e)}")
240
 
241
  def validate_and_get_file(uploaded_file, url_string, file_type, temp_dir):
242
  has_upload = uploaded_file is not None