lokesh341 commited on
Commit
ad58a48
Β·
verified Β·
1 Parent(s): 014e678

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -27
app.py CHANGED
@@ -1,41 +1,140 @@
1
- # app.py for Hugging Face Spaces
2
 
3
  import gradio as gr
4
  from fpdf import FPDF
 
 
 
5
 
6
  def generate_pdf(names, image_files):
 
 
 
 
7
  names_list = [n.strip() for n in names.split(',') if n.strip()]
8
 
 
9
  if not image_files:
10
- return "Please upload at least one image."
11
 
 
12
  if len(names_list) != len(image_files):
13
- return f"Mismatch: {len(names_list)} names but {len(image_files)} images. Please provide matching numbers."
14
-
15
- pdf = FPDF()
16
-
17
- for name, img_path in zip(names_list, image_files):
18
- pdf.add_page()
19
- pdf.set_font('helvetica', 'B', 16)
20
- pdf.cell(0, 10, name, ln=1, align='C')
21
- try:
22
- pdf.image(img_path, x=50, y=30, w=100) # Adjust positions and size as needed
23
- except Exception as e:
24
- return f"Error adding image: {str(e)}"
25
-
26
- output_path = "output.pdf"
27
- pdf.output(output_path)
28
- return output_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- with gr.Blocks() as demo:
31
- gr.Markdown("# PDF Generator App")
32
- gr.Markdown("Enter comma-separated names and upload corresponding images to generate a PDF.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- names_input = gr.Textbox(label="Names (comma-separated)", placeholder="Name1, Name2, Name3")
35
- images_input = gr.File(label="Upload Images", file_count="multiple", file_types=[".jpg", ".png", ".jpeg"])
36
- generate_btn = gr.Button("Generate PDF")
37
- output_file = gr.File(label="Download PDF")
38
 
39
- generate_btn.click(fn=generate_pdf, inputs=[names_input, images_input], outputs=output_file)
 
 
 
 
 
40
 
41
- demo.launch()
 
 
1
+ # app.py - Fixed PDF Generator with better error handling and UI
2
 
3
  import gradio as gr
4
  from fpdf import FPDF
5
+ import os
6
+ import tempfile
7
+ from pathlib import Path
8
 
9
  def generate_pdf(names, image_files):
10
+ # Clean and validate names
11
+ if not names or names.strip() == "":
12
+ return None, "❌ Please enter at least one name!"
13
+
14
  names_list = [n.strip() for n in names.split(',') if n.strip()]
15
 
16
+ # Validate images
17
  if not image_files:
18
+ return None, "❌ Please upload at least one image!"
19
 
20
+ # Check if number of names matches number of images
21
  if len(names_list) != len(image_files):
22
+ return None, f"❌ Mismatch! You have {len(names_list)} names but {len(image_files)} images. Please match the counts."
23
+
24
+ try:
25
+ pdf = FPDF()
26
+ pdf.set_auto_page_break(auto=True, margin=15)
27
+
28
+ for i, (name, img_path) in enumerate(zip(names_list, image_files)):
29
+ # Add new page for each item
30
+ pdf.add_page()
31
+
32
+ # Add title/name
33
+ pdf.set_font('helvetica', 'B', 20)
34
+ pdf.set_text_color(50, 50, 50)
35
+ pdf.cell(0, 15, name.upper(), ln=1, align='C')
36
+
37
+ # Add subtitle
38
+ pdf.set_font('helvetica', '', 12)
39
+ pdf.cell(0, 10, f"ID: {i+1}", ln=1, align='C')
40
+
41
+ # Add image with error handling
42
+ try:
43
+ # Get image dimensions for better scaling
44
+ img_width = 120
45
+ img_height = pdf.get_string_width(name) * 0.8 # Approximate
46
+
47
+ # Calculate position to center image
48
+ page_width = pdf.w
49
+ x_pos = (page_width - img_width) / 2
50
+
51
+ pdf.image(img_path, x=x_pos, y=40, w=img_width)
52
+
53
+ except Exception as img_error:
54
+ # If image fails, add placeholder text
55
+ pdf.set_font('helvetica', 'I', 14)
56
+ pdf.set_text_color(200, 50, 50)
57
+ pdf.cell(0, 10, f"Image {i+1} could not be loaded", ln=1, align='C')
58
+ pdf.cell(0, 10, str(img_error), ln=1, align='C')
59
+
60
+ # Create temporary file for output
61
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
62
+ output_path = tmp_file.name
63
+ pdf.output(output_path)
64
+
65
+ success_msg = f"βœ… Successfully generated PDF with {len(names_list)} pages!"
66
+ return output_path, success_msg
67
+
68
+ except Exception as e:
69
+ return None, f"❌ Error generating PDF: {str(e)}"
70
 
71
+ # Create beautiful UI
72
+ with gr.Blocks(
73
+ title="πŸ“„ PDF Generator Pro",
74
+ theme=gr.themes.Soft(),
75
+ css="""
76
+ .gradio-container {max-width: 800px; margin: auto;}
77
+ .status-message {font-size: 16px; padding: 10px; border-radius: 5px; margin: 10px 0;}
78
+ .success {background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;}
79
+ .error {background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;}
80
+ """
81
+ ) as demo:
82
+
83
+ gr.Markdown("""
84
+ # πŸ“„ PDF Generator Pro
85
+ ### Create professional PDFs with names and images
86
+ **Instructions:**
87
+ 1. Enter names separated by commas (e.g., "John Doe, Jane Smith, Bob Wilson")
88
+ 2. Upload the same number of images as names
89
+ 3. Click Generate PDF
90
+ 4. Download your professional PDF!
91
+ """)
92
+
93
+ with gr.Row():
94
+ with gr.Column(scale=1):
95
+ names_input = gr.Textbox(
96
+ label="πŸ‘₯ Names (comma-separated)",
97
+ placeholder="John Doe, Jane Smith, Bob Wilson",
98
+ lines=3,
99
+ elem_id="names-input"
100
+ )
101
+
102
+ with gr.Row():
103
+ generate_btn = gr.Button("πŸš€ Generate PDF", variant="primary", size="lg")
104
+ clear_btn = gr.Button("πŸ—‘οΈ Clear All", variant="secondary")
105
+
106
+ with gr.Column(scale=1):
107
+ images_input = gr.File(
108
+ label="πŸ–ΌοΈ Upload Images",
109
+ file_count="multiple",
110
+ file_types=["image"],
111
+ elem_id="images-input"
112
+ )
113
+
114
+ status_output = gr.Markdown("", elem_classes="status-message")
115
+ pdf_output = gr.File(label="πŸ“₯ Download Your PDF", elem_id="pdf-output")
116
+
117
+ # Event handlers
118
+ def clear_all():
119
+ return "", None, gr.update(value=[]), "Ready to create new PDF!"
120
+
121
+ generate_btn.click(
122
+ fn=generate_pdf,
123
+ inputs=[names_input, images_input],
124
+ outputs=[pdf_output, status_output]
125
+ )
126
 
127
+ clear_btn.click(
128
+ fn=clear_all,
129
+ outputs=[names_input, pdf_output, images_input, status_output]
130
+ )
131
 
132
+ # Auto-validation example
133
+ names_input.change(
134
+ fn=lambda names: (None, f"πŸ“ Found {len([n.strip() for n in names.split(',') if n.strip()])} names") if names else (None, ""),
135
+ inputs=[names_input],
136
+ outputs=[pdf_output, status_output]
137
+ )
138
 
139
+ if __name__ == "__main__":
140
+ demo.launch()