VectorV17 commited on
Commit
400efd8
·
verified ·
1 Parent(s): c90a9f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -97
app.py CHANGED
@@ -2,7 +2,7 @@ import os
2
  import io
3
  import gradio as gr
4
  import spaces
5
- from PIL import Image
6
  from huggingface_hub import InferenceClient
7
  from reportlab.pdfgen import canvas
8
  from reportlab.lib.pagesizes import A4
@@ -10,140 +10,120 @@ from reportlab.lib import colors
10
  from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
11
  from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image as RLImage, Table, TableStyle
12
 
13
- # --- AUTHENTICATION & CLIENT ---
14
  hf_token = os.getenv("HF_TOKEN")
15
  client = InferenceClient("black-forest-labs/FLUX.1-schnell", token=hf_token)
16
 
17
- # --- DETERMINISTIC TECHNICAL DATA ---
18
- # These datasets replicate the precise tabular format seen in industry tech packs
19
- POM_GRADED_SPEC_TABLE = [
20
- ["Pos", "Point of measurement", "S (cm)", "M (cm)", "L (cm)", "XL (cm)", "XXL (cm)"],
21
- ["A", "Body length (hsp->hem)", "67.0", "68.5", "69.0", "70.5", "72.0"],
22
- ["B", "Chest (ah->ah)", "50.0", "52.0", "54.0", "56.0", "58.0"],
23
- ["C", "Shoulder (across joints)", "44.5", "45.5", "46.5", "47.5", "48.5"],
24
- ["D", "Armhole (depth)", "21.0", "22.0", "23.0", "24.0", "25.0"],
25
- ["E", "Sleeve length (sp->sleeve)", "66.0", "67.0", "68.0", "69.0", "70.0"],
26
- ["F", "pocket length", "12.5", "12.5", "13.0", "13.0", "14.0"],
27
- ["G", "pocket width", "12.0", "12.0", "12.0", "12.5", "13.5"],
28
  ]
29
 
30
- BOM_TABLE_DATA = [
31
- ["Material Component", "Detail / Specs", "Supplier", "Note"],
32
- ["Main Fabric", "Jersey, 100% Combed Cotton, 180 GSM", "Graph Tick", "Stock"],
33
- ["Rib Fabric", "1x1 Rib knit (Collar/Cuffs)", "Graph Tick", "DTM"],
34
- ["Threads", "Polyester, Tex 40", "TBD", "DTM"],
35
- ["Buttons", "Snap button, Gold Finish", "Graph Tick", "Front Placket"],
36
- ]
37
-
38
- CONSTRUCTION_DETAILS = {
39
- "Labels": "Main label sewing inside yoke 2.5 cm below neck seam.",
40
- "Sewing": "Twin needle stitch on bottom hem and sleeve hem. Tape reinforcement across back neck.",
41
- "Packing": "Fold according to standards. Polybag individually. 12 pcs per carton."
42
- }
 
 
 
 
 
 
 
 
43
 
44
- # --- PDF GENERATION ENGINE ---
45
- def create_pdf_tech_pack(front_sketch_pil, back_sketch_pil, style_name, g_type, prompt_text, filename="tech_pack.pdf"):
46
- # Convert PIL to Bytes for ReportLab
47
  img_b_f, img_b_b = io.BytesIO(), io.BytesIO()
48
- front_sketch_pil.save(img_b_f, format='PNG')
49
- back_sketch_pil.save(img_b_b, format='PNG')
50
  img_b_f.seek(0), img_b_b.seek(0)
51
 
52
- doc = SimpleDocTemplate(filename, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=30)
53
  styles = getSampleStyleSheet()
54
-
55
- # --- RECTIFICATION: REGISTER CUSTOM STYLES ---
56
  if 'Headline' not in styles:
57
  styles.add(ParagraphStyle(name='Headline', parent=styles['Heading1'], fontSize=14, alignment=1, textColor=colors.white))
58
  if 'SectionHeader' not in styles:
59
  styles.add(ParagraphStyle(name='SectionHeader', parent=styles['Heading1'], fontSize=12, textColor=colors.black, spaceAfter=10))
60
 
61
  story = []
62
-
63
- # 1. Header Table (Mimics image_7 header)
64
- header_data = [
65
- [Paragraph("<b>TECHNICAL PACKAGE</b>", styles['Headline']), "", f"Garment: {g_type.upper()}"],
66
- ["Style Name:", style_name, ""],
67
- ["Style Number:", "W-2026-AUTO", "Supplier: AI Tech Studio"],
68
- ]
69
- header_table = Table(header_data, colWidths=[150, 250, 140])
70
- header_table.setStyle(TableStyle([
71
- ('FONTNAME', (0,0), (-1,-1), 'Helvetica'),
72
- ('GRID', (0,0), (-1,-1), 1, colors.black),
73
- ('BACKGROUND', (0,0), (0,0), colors.black),
74
- ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
75
- ]))
76
- story.append(header_table)
77
  story.append(Spacer(1, 20))
78
 
79
- # 2. Sketches Section
80
- story.append(Paragraph("<b>SECTION 1: TECHNICAL DESIGN SKETCHES</b>", styles['SectionHeader']))
81
- sketch_table = Table([
82
- [RLImage(img_b_f, width=250, height=250), RLImage(img_b_b, width=250, height=250)],
83
- [Paragraph("FRONT VIEW", styles['Normal']), Paragraph("BACK VIEW", styles['Normal'])]
84
- ])
85
- sketch_table.setStyle(TableStyle([('ALIGN', (0,0), (-1,-1), 'CENTER')]))
86
- story.append(sketch_table)
87
- story.append(Spacer(1, 30))
88
 
89
- # 3. POM Spec Sheet (Exactly matching user image)
90
- story.append(Paragraph("<b>SECTION 2: GRADED SPECIFICATION SHEET (POM)</b>", styles['SectionHeader']))
91
- spec_table = Table(POM_GRADED_SPEC_TABLE, colWidths=[40, 220, 50, 50, 50, 50, 50])
92
- spec_table.setStyle(TableStyle([
93
- ('GRID', (0,0), (-1,-1), 1, colors.black),
94
- ('BACKGROUND', (0,0), (-1,0), colors.lightgrey),
95
- ('BACKGROUND', (3,1), (3,-1), colors.yellow), # Highlight M size
96
- ('ALIGN', (0,0), (-1,-1), 'CENTER'),
97
- ('ALIGN', (1,1), (1,-1), 'LEFT'),
98
- ]))
99
  story.append(spec_table)
100
- story.append(Spacer(1, 30))
101
-
102
- # 4. BOM Section
103
- story.append(Paragraph("<b>SECTION 3: BILL OF MATERIALS (BOM)</b>", styles['SectionHeader']))
104
- bom_table = Table(BOM_TABLE_DATA, colWidths=[130, 180, 100, 100])
105
- bom_table.setStyle(TableStyle([('GRID', (0,0), (-1,-1), 1, colors.black), ('BACKGROUND', (0,0), (-1,0), colors.lightgrey)]))
106
- story.append(bom_table)
107
 
108
  doc.build(story)
109
  return filename
110
 
111
  # --- GRADIO INTERFACE ---
112
- with gr.Blocks() as demo:
113
- gr.Markdown("# 👔 AI Tech-Pack Studio (Multi-Page PDF Generator)")
114
 
115
  with gr.Row():
116
- with gr.Column():
117
- with gr.Row():
118
- img_front = gr.Image(label="Front Photo", type="filepath")
119
- img_back = gr.Image(label="Back Photo", type="filepath")
120
- style_name = gr.Textbox(label="Style Name", value="G-STUDIO-V1")
 
121
  g_type = gr.Dropdown(["T-Shirt", "Shirt", "Hoodie", "Jacket"], value="T-Shirt", label="Garment Type")
122
- prompt = gr.Textbox(label="Technical Details", value="Slim fit, contrast zipper, ribbed cuffs")
123
- submit_btn = gr.Button("🚀 Generate Full Tech Pack", variant="primary")
124
 
125
- with gr.Column():
126
- output_file = gr.File(label="Download PDF Tech Pack")
127
- status = gr.Textbox(label="Status", interactive=False)
 
 
 
128
 
129
  @spaces.GPU(duration=180)
130
- def process(f_in, b_in, s_name, gt, u_prompt):
131
- if not f_in or not b_in: return None, "❌ Upload both images."
132
 
133
  try:
134
- # Generate sketches via API
135
- style_desc = "Technical flat sketch, black/white vector, clean lines, white background, no model."
136
  f_sketch = client.text_to_image(f"Front view: {gt}, {u_prompt}, {style_desc}")
137
  b_sketch = client.text_to_image(f"Back view: {gt}, {u_prompt}, {style_desc}")
138
 
139
- # Create PDF on CPU
140
- fname = f"{s_name.replace(' ', '_').lower()}_techpack.pdf"
 
 
 
141
  pdf_path = create_pdf_tech_pack(f_sketch, b_sketch, s_name, gt, u_prompt, fname)
142
- return pdf_path, "✅ Tech Pack Generated Successfully."
 
143
  except Exception as e:
144
- return None, f"❌ Error: {str(e)}"
145
 
146
- submit_btn.click(process, [img_front, img_back, style_name, g_type, prompt], [output_file, status])
 
 
 
 
147
 
148
- # Launch with theme here to avoid Gradio 6.0 warnings
149
  demo.launch(theme=gr.themes.Soft())
 
2
  import io
3
  import gradio as gr
4
  import spaces
5
+ from PIL import Image, ImageDraw
6
  from huggingface_hub import InferenceClient
7
  from reportlab.pdfgen import canvas
8
  from reportlab.lib.pagesizes import A4
 
10
  from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
11
  from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image as RLImage, Table, TableStyle
12
 
13
+ # --- AUTHENTICATION ---
14
  hf_token = os.getenv("HF_TOKEN")
15
  client = InferenceClient("black-forest-labs/FLUX.1-schnell", token=hf_token)
16
 
17
+ # --- DATA TEMPLATES ---
18
+ POM_DATA = [
19
+ ["Pos", "Measurement", "S", "M", "L", "XL"],
20
+ ["A", "Body length", "67.0", "68.5", "69.0", "70.5"],
21
+ ["B", "Chest width", "50.0", "52.0", "54.0", "56.0"],
22
+ ["C", "Shoulder", "44.5", "45.5", "46.5", "47.5"],
 
 
 
 
 
23
  ]
24
 
25
+ # --- PDF & PREVIEW GENERATION ---
26
+ def generate_preview_image(front, back, style_name, g_type):
27
+ """Creates a single-sheet visual preview for the RHS display."""
28
+ preview = Image.new("RGB", (800, 1000), "white")
29
+ draw = ImageDraw.Draw(preview)
30
+
31
+ # Header
32
+ draw.rectangle([0, 0, 800, 80], fill="black")
33
+ draw.text((20, 30), f"TECH PACK PREVIEW: {style_name.upper()}", fill="white")
34
+
35
+ # Sketches
36
+ f_thumb = front.resize((350, 350))
37
+ b_thumb = back.resize((350, 350))
38
+ preview.paste(f_thumb, (30, 120))
39
+ preview.paste(b_thumb, (420, 120))
40
+
41
+ # Dummy Table Preview
42
+ draw.text((30, 500), "GRADED SPECIFICATION SHEET (POM)", fill="black")
43
+ draw.rectangle([30, 520, 770, 700], outline="black", width=1)
44
+
45
+ return preview
46
 
47
+ def create_pdf_tech_pack(front_sketch, back_sketch, style_name, g_type, prompt_text, filename):
 
 
48
  img_b_f, img_b_b = io.BytesIO(), io.BytesIO()
49
+ front_sketch.save(img_b_f, format='PNG')
50
+ back_sketch.save(img_b_b, format='PNG')
51
  img_b_f.seek(0), img_b_b.seek(0)
52
 
53
+ doc = SimpleDocTemplate(filename, pagesize=A4)
54
  styles = getSampleStyleSheet()
55
+
 
56
  if 'Headline' not in styles:
57
  styles.add(ParagraphStyle(name='Headline', parent=styles['Heading1'], fontSize=14, alignment=1, textColor=colors.white))
58
  if 'SectionHeader' not in styles:
59
  styles.add(ParagraphStyle(name='SectionHeader', parent=styles['Heading1'], fontSize=12, textColor=colors.black, spaceAfter=10))
60
 
61
  story = []
62
+ header = Table([[Paragraph("<b>TECHNICAL PACKAGE</b>", styles['Headline']), "", f"Type: {g_type}"]], colWidths=[150, 250, 140])
63
+ header.setStyle(TableStyle([('BACKGROUND', (0,0), (0,0), colors.black), ('GRID', (0,0), (-1,-1), 1, colors.black)]))
64
+ story.append(header)
 
 
 
 
 
 
 
 
 
 
 
 
65
  story.append(Spacer(1, 20))
66
 
67
+ sketches = Table([[RLImage(img_b_f, width=240, height=240), RLImage(img_b_b, width=240, height=240)]])
68
+ story.append(sketches)
 
 
 
 
 
 
 
69
 
70
+ # POM Table
71
+ story.append(Spacer(1, 20))
72
+ story.append(Paragraph("<b>SECTION 2: MEASUREMENTS (POM)</b>", styles['SectionHeader']))
73
+ spec_table = Table(POM_DATA, colWidths=[40, 200, 50, 50, 50, 50])
74
+ spec_table.setStyle(TableStyle([('GRID', (0,0), (-1,-1), 1, colors.black), ('BACKGROUND', (0,0), (-1,0), colors.lightgrey)]))
 
 
 
 
 
75
  story.append(spec_table)
 
 
 
 
 
 
 
76
 
77
  doc.build(story)
78
  return filename
79
 
80
  # --- GRADIO INTERFACE ---
81
+ with gr.Blocks(css=".gradio-container {background-color: #f8f9fa}") as demo:
82
+ gr.Markdown("# 👔 AI Tech-Pack Studio Pro")
83
 
84
  with gr.Row():
85
+ # LEFT COLUMN: INPUTS
86
+ with gr.Column(scale=1):
87
+ gr.Markdown("### 🛠 Design Controls")
88
+ img_front = gr.Image(label="Front Reference", type="filepath")
89
+ img_back = gr.Image(label="Back Reference", type="filepath")
90
+ style_name = gr.Textbox(label="Style Name", value="G-STUDIO-JACKET")
91
  g_type = gr.Dropdown(["T-Shirt", "Shirt", "Hoodie", "Jacket"], value="T-Shirt", label="Garment Type")
92
+ prompt = gr.Textbox(label="Technical Instructions", value="Minimalist, rib-knit collar")
93
+ submit_btn = gr.Button("🚀 Generate Tech Pack", variant="primary")
94
 
95
+ # RIGHT COLUMN: PREVIEW & DOWNLOAD
96
+ with gr.Column(scale=1):
97
+ gr.Markdown("### 📄 Tech Pack Sheet Preview")
98
+ preview_display = gr.Image(label="One-Sheet Preview", interactive=False)
99
+ download_file = gr.File(label="Download Full Multi-Page PDF")
100
+ status = gr.Textbox(label="System Status", interactive=False)
101
 
102
  @spaces.GPU(duration=180)
103
+ def process_and_preview(f_in, b_in, s_name, gt, u_prompt):
104
+ if not f_in or not b_in: return None, None, "❌ Upload images first."
105
 
106
  try:
107
+ # 1. AI Generation
108
+ style_desc = "Technical flat sketch, black/white vector style, white background."
109
  f_sketch = client.text_to_image(f"Front view: {gt}, {u_prompt}, {style_desc}")
110
  b_sketch = client.text_to_image(f"Back view: {gt}, {u_prompt}, {style_desc}")
111
 
112
+ # 2. Generate RHS Preview (Image)
113
+ preview_img = generate_preview_image(f_sketch, b_sketch, s_name, gt)
114
+
115
+ # 3. Generate Full PDF (Downloadable)
116
+ fname = f"{s_name.replace(' ', '_').lower()}.pdf"
117
  pdf_path = create_pdf_tech_pack(f_sketch, b_sketch, s_name, gt, u_prompt, fname)
118
+
119
+ return preview_img, pdf_path, "✅ Generated Successfully."
120
  except Exception as e:
121
+ return None, None, f"❌ Error: {str(e)}"
122
 
123
+ submit_btn.click(
124
+ process_and_preview,
125
+ [img_front, img_back, style_name, g_type, prompt],
126
+ [preview_display, download_file, status]
127
+ )
128
 
 
129
  demo.launch(theme=gr.themes.Soft())