phxdev commited on
Commit
e5ec1ba
Β·
verified Β·
1 Parent(s): 6b28843

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +206 -13
  2. requirements.txt +5 -1
app.py CHANGED
@@ -5,10 +5,20 @@ import os
5
  from gradio_client import Client
6
  import asyncio
7
  import json
 
 
 
 
 
 
 
 
 
8
 
9
  # Initialize the text generation pipeline and MCP client
10
  generator = None
11
  mcp_client = None
 
12
 
13
  # MCP client configuration
14
  MCP_ENDPOINTS = {
@@ -72,6 +82,34 @@ def initialize_mcp_client():
72
  except Exception as e:
73
  return f"MCP client initialization failed: {str(e)}"
74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  def generate_with_mcp(topic, target_audience, key_points, tone, length, model_choice="local"):
76
  """Generate one-pager using MCP client or local model"""
77
 
@@ -225,11 +263,130 @@ def import_date():
225
  from datetime import datetime
226
  return datetime.now().strftime("%B %d, %Y")
227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  # Create the Gradio interface
229
  def create_interface():
230
  with gr.Blocks(title="One-Pager Generator", theme=gr.themes.Soft()) as demo:
231
  gr.Markdown("# πŸ“„ AI One-Pager Generator")
232
- gr.Markdown("Generate professional business documents with visual formatting - NOT markdown! Perfect for printing and presentations.")
233
 
234
  with gr.Row():
235
  with gr.Column(scale=1):
@@ -273,16 +430,35 @@ def create_interface():
273
  info="Choose between local Qwen model or MCP-connected external services"
274
  )
275
 
 
 
 
 
 
 
276
  generate_btn = gr.Button("πŸš€ Generate One-Pager", variant="primary")
277
 
278
  with gr.Column(scale=2):
279
- output_text = gr.Textbox(
280
- label="Generated One-Pager",
281
- lines=25,
282
- max_lines=35,
283
- show_copy_button=True,
284
- placeholder="Your generated one-pager will appear here..."
285
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
286
 
287
  with gr.Row():
288
  gr.Markdown("""
@@ -295,21 +471,38 @@ def create_interface():
295
  """)
296
 
297
  # Connect the generate button to the function
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  generate_btn.click(
299
- fn=generate_with_mcp,
300
- inputs=[topic_input, audience_input, keypoints_input, tone_dropdown, length_dropdown, model_dropdown],
301
- outputs=output_text
302
  )
303
 
304
  return demo
305
 
306
  # Initialize model and launch
307
  if __name__ == "__main__":
308
- print("πŸš€ Starting One-Pager Generator with Qwen 2.5-7B and MCP...")
309
- print("πŸ“₯ Loading AI model...")
310
  model_status = initialize_model()
311
  print(f"βœ… {model_status}")
312
 
 
 
 
 
313
  print("πŸ”— Initializing MCP client...")
314
  mcp_status = initialize_mcp_client()
315
  print(f"βœ… {mcp_status}")
 
5
  from gradio_client import Client
6
  import asyncio
7
  import json
8
+ from reportlab.lib.pagesizes import letter
9
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image as RLImage
10
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
11
+ from reportlab.lib.units import inch
12
+ from reportlab.lib import colors
13
+ from diffusers import FluxPipeline
14
+ from PIL import Image
15
+ import io
16
+ import tempfile
17
 
18
  # Initialize the text generation pipeline and MCP client
19
  generator = None
20
  mcp_client = None
21
+ image_generator = None
22
 
23
  # MCP client configuration
24
  MCP_ENDPOINTS = {
 
82
  except Exception as e:
83
  return f"MCP client initialization failed: {str(e)}"
84
 
85
+ def initialize_image_generator():
86
+ """Initialize FLUX Schnell for image generation"""
87
+ global image_generator
88
+ try:
89
+ # Try to load FLUX Schnell
90
+ image_generator = FluxPipeline.from_pretrained(
91
+ "black-forest-labs/FLUX.1-schnell",
92
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
93
+ device_map="auto" if torch.cuda.is_available() else None
94
+ )
95
+ if not torch.cuda.is_available():
96
+ image_generator = image_generator.to("cpu")
97
+ return "FLUX Schnell image generator loaded successfully!"
98
+ except Exception as e:
99
+ # Fallback to a smaller model if FLUX fails
100
+ try:
101
+ from diffusers import StableDiffusionPipeline
102
+ image_generator = StableDiffusionPipeline.from_pretrained(
103
+ "runwayml/stable-diffusion-v1-5",
104
+ torch_dtype=torch.float32,
105
+ safety_checker=None,
106
+ requires_safety_checker=False
107
+ )
108
+ image_generator = image_generator.to("cpu")
109
+ return "Fallback to Stable Diffusion v1.5 for image generation!"
110
+ except Exception as e2:
111
+ return f"Image generation initialization failed: {str(e)}, Fallback: {str(e2)}"
112
+
113
  def generate_with_mcp(topic, target_audience, key_points, tone, length, model_choice="local"):
114
  """Generate one-pager using MCP client or local model"""
115
 
 
263
  from datetime import datetime
264
  return datetime.now().strftime("%B %d, %Y")
265
 
266
+ def generate_header_image(topic, tone):
267
+ """Generate a header image for the one-pager using FLUX Schnell"""
268
+ global image_generator
269
+
270
+ if image_generator is None:
271
+ return None
272
+
273
+ try:
274
+ # Create a professional prompt for the header image
275
+ image_prompt = f"Professional business illustration for {topic}, {tone.lower()} style, corporate presentation, clean design, business graphics, high quality, no text"
276
+
277
+ # Generate image
278
+ image = image_generator(
279
+ prompt=image_prompt,
280
+ num_inference_steps=4, # Fast generation with Schnell
281
+ guidance_scale=0.0, # FLUX Schnell doesn't need guidance
282
+ height=256,
283
+ width=512
284
+ ).images[0]
285
+
286
+ return image
287
+
288
+ except Exception as e:
289
+ print(f"Image generation failed: {str(e)}")
290
+ return None
291
+
292
+ def export_to_pdf(content, topic, header_image=None):
293
+ """Export the one-pager content to PDF"""
294
+ try:
295
+ # Create a temporary file for the PDF
296
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
297
+ pdf_path = tmp_file.name
298
+
299
+ # Create PDF document
300
+ doc = SimpleDocTemplate(pdf_path, pagesize=letter, topMargin=0.5*inch)
301
+ styles = getSampleStyleSheet()
302
+
303
+ # Custom styles
304
+ title_style = ParagraphStyle(
305
+ 'CustomTitle',
306
+ parent=styles['Heading1'],
307
+ fontSize=16,
308
+ spaceAfter=20,
309
+ textColor=colors.darkblue,
310
+ alignment=1 # Center alignment
311
+ )
312
+
313
+ body_style = ParagraphStyle(
314
+ 'CustomBody',
315
+ parent=styles['Normal'],
316
+ fontSize=10,
317
+ fontName='Courier', # Monospace font to preserve ASCII formatting
318
+ leftIndent=0,
319
+ rightIndent=0
320
+ )
321
+
322
+ # Build PDF content
323
+ story = []
324
+
325
+ # Add header image if available
326
+ if header_image:
327
+ try:
328
+ # Save image temporarily
329
+ img_buffer = io.BytesIO()
330
+ header_image.save(img_buffer, format='PNG')
331
+ img_buffer.seek(0)
332
+
333
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as img_file:
334
+ img_file.write(img_buffer.getvalue())
335
+ img_path = img_file.name
336
+
337
+ # Add image to PDF
338
+ img = RLImage(img_path, width=6*inch, height=3*inch)
339
+ story.append(img)
340
+ story.append(Spacer(1, 20))
341
+
342
+ # Clean up temp image file
343
+ os.unlink(img_path)
344
+
345
+ except Exception as e:
346
+ print(f"Failed to add image to PDF: {str(e)}")
347
+
348
+ # Add title
349
+ story.append(Paragraph(f"Business Document: {topic}", title_style))
350
+ story.append(Spacer(1, 20))
351
+
352
+ # Add content (preserve formatting)
353
+ content_lines = content.split('\n')
354
+ for line in content_lines:
355
+ if line.strip():
356
+ story.append(Paragraph(line.replace('<', '&lt;').replace('>', '&gt;'), body_style))
357
+ else:
358
+ story.append(Spacer(1, 6))
359
+
360
+ # Build PDF
361
+ doc.build(story)
362
+
363
+ return pdf_path
364
+
365
+ except Exception as e:
366
+ print(f"PDF export failed: {str(e)}")
367
+ return None
368
+
369
+ def generate_complete_onepager(topic, target_audience, key_points, tone, length, model_choice="local", include_image=True):
370
+ """Generate complete one-pager with optional image and return both content and PDF"""
371
+
372
+ # Generate the text content
373
+ content = generate_with_mcp(topic, target_audience, key_points, tone, length, model_choice)
374
+
375
+ # Generate header image if requested
376
+ header_image = None
377
+ if include_image and image_generator is not None:
378
+ header_image = generate_header_image(topic, tone)
379
+
380
+ # Generate PDF
381
+ pdf_path = export_to_pdf(content, topic, header_image)
382
+
383
+ return content, pdf_path, header_image
384
+
385
  # Create the Gradio interface
386
  def create_interface():
387
  with gr.Blocks(title="One-Pager Generator", theme=gr.themes.Soft()) as demo:
388
  gr.Markdown("# πŸ“„ AI One-Pager Generator")
389
+ gr.Markdown("Generate professional business documents with FLUX Schnell images and PDF export! Visual formatting, not markdown.")
390
 
391
  with gr.Row():
392
  with gr.Column(scale=1):
 
430
  info="Choose between local Qwen model or MCP-connected external services"
431
  )
432
 
433
+ include_image_checkbox = gr.Checkbox(
434
+ label="Generate Header Image",
435
+ value=True,
436
+ info="Use FLUX Schnell to generate a professional header image"
437
+ )
438
+
439
  generate_btn = gr.Button("πŸš€ Generate One-Pager", variant="primary")
440
 
441
  with gr.Column(scale=2):
442
+ with gr.Row():
443
+ output_text = gr.Textbox(
444
+ label="Generated One-Pager",
445
+ lines=20,
446
+ max_lines=30,
447
+ show_copy_button=True,
448
+ placeholder="Your generated one-pager will appear here...",
449
+ scale=2
450
+ )
451
+ generated_image = gr.Image(
452
+ label="Header Image",
453
+ scale=1,
454
+ height=200
455
+ )
456
+
457
+ with gr.Row():
458
+ pdf_download = gr.File(
459
+ label="Download PDF",
460
+ visible=False
461
+ )
462
 
463
  with gr.Row():
464
  gr.Markdown("""
 
471
  """)
472
 
473
  # Connect the generate button to the function
474
+ def generate_and_display(topic, audience, keypoints, tone, length, model, include_image):
475
+ content, pdf_path, header_image = generate_complete_onepager(
476
+ topic, audience, keypoints, tone, length, model, include_image
477
+ )
478
+
479
+ # Return outputs for all components
480
+ pdf_visible = pdf_path is not None
481
+ return (
482
+ content, # output_text
483
+ header_image, # generated_image
484
+ gr.File(value=pdf_path, visible=pdf_visible) # pdf_download
485
+ )
486
+
487
  generate_btn.click(
488
+ fn=generate_and_display,
489
+ inputs=[topic_input, audience_input, keypoints_input, tone_dropdown, length_dropdown, model_dropdown, include_image_checkbox],
490
+ outputs=[output_text, generated_image, pdf_download]
491
  )
492
 
493
  return demo
494
 
495
  # Initialize model and launch
496
  if __name__ == "__main__":
497
+ print("πŸš€ Starting One-Pager Generator with Qwen 2.5-7B, MCP, and FLUX Schnell...")
498
+ print("πŸ“₯ Loading AI text model...")
499
  model_status = initialize_model()
500
  print(f"βœ… {model_status}")
501
 
502
+ print("🎨 Loading FLUX Schnell image generator...")
503
+ image_status = initialize_image_generator()
504
+ print(f"βœ… {image_status}")
505
+
506
  print("πŸ”— Initializing MCP client...")
507
  mcp_status = initialize_mcp_client()
508
  print(f"βœ… {mcp_status}")
requirements.txt CHANGED
@@ -6,4 +6,8 @@ tokenizers
6
  accelerate
7
  psutil
8
  mcp
9
- gradio_client
 
 
 
 
 
6
  accelerate
7
  psutil
8
  mcp
9
+ gradio_client
10
+ reportlab
11
+ fpdf2
12
+ diffusers
13
+ pillow