Spaces:
Sleeping

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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -103
app.py CHANGED
@@ -1,129 +1,103 @@
1
  import os
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
9
- 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 ---
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())
 
1
  import os
2
  import io
3
  import gradio as gr
 
4
  from PIL import Image, ImageDraw
5
  from huggingface_hub import InferenceClient
 
 
 
 
 
6
 
7
+ # --- API CONFIGURATION ---
8
+ # We use FLUX.1-schnell via the Inference API to save CPU resources.
9
+ model_id = "black-forest-labs/FLUX.1-schnell"
10
+ client = InferenceClient(model=model_id, token=os.getenv("HF_TOKEN"))
11
 
12
+ def create_tech_pack_canvas(front_sketch, back_sketch, prompt_text, garment_type):
13
+ # Professional A4 Landscape canvas (1200x800)
14
+ canvas = Image.new("RGB", (1200, 800), "white")
15
+ draw = ImageDraw.Draw(canvas)
16
+
17
+ # 1. Header Bar
18
+ draw.rectangle([0, 0, 1200, 70], fill=(33, 33, 33))
19
+ draw.text((30, 25), f"TECHNICAL SPECIFICATION: {garment_type.upper()}", fill="white")
20
+ draw.text((1000, 25), "AI GENERATED DRAFT", fill="#AAAAAA")
21
 
22
+ # 2. Process and Placement
23
+ # Resize generated sketches to fit the layout
24
+ front_sketch = front_sketch.resize((500, 500))
25
+ back_sketch = back_sketch.resize((500, 500))
 
26
 
27
+ canvas.paste(front_sketch, (50, 120))
28
+ canvas.paste(back_sketch, (650, 120))
 
29
 
30
+ # 3. Labels and Annotations
31
+ draw.text((250, 630), "FRONT VIEW", fill="black")
32
+ draw.text((850, 630), "BACK VIEW", fill="black")
 
 
33
 
34
+ # 4. Footer Data Box
35
+ draw.rectangle([50, 680, 1150, 770], outline="black", width=2)
36
+ draw.text((70, 700), f"Design Notes: {prompt_text[:100]}...", fill="black")
37
+ draw.text((70, 730), "Recommended Fabric: Jersey/Interlock Cotton", fill="gray")
38
 
39
+ return canvas
40
 
41
+ def generate_tech_pack(front_img, back_img, user_prompt, garment_type):
42
+ if not os.getenv("HF_TOKEN"):
43
+ return None, "❌ Error: HF_TOKEN not found in Space Secrets."
 
 
 
 
 
44
 
45
+ if not front_img or not back_img:
46
+ return None, "⚠️ Please upload both front and back reference images."
 
 
47
 
48
+ # Technical prompt engineering to ensure "Klein" style flat sketches
49
+ base_prompt = (
50
+ f"Professional technical apparel flat sketch of a {garment_type}, {user_prompt}, "
51
+ "black and white vector style, clean outlines, industrial design standard, "
52
+ "white background, no shadows, no human model."
53
+ )
 
 
 
 
 
 
 
 
 
54
 
55
+ try:
56
+ # Calling the API for Front and Back
57
+ print("Generating Front Sketch...")
58
+ front_sketch = client.text_to_image(f"Front view: {base_prompt}")
59
+
60
+ print("Generating Back Sketch...")
61
+ back_sketch = client.text_to_image(f"Back view: {base_prompt}")
62
+
63
+ # Combine into the Tech Pack Sheet
64
+ final_sheet = create_tech_pack_canvas(front_sketch, back_sketch, user_prompt, garment_type)
65
+
66
+ return final_sheet, "✅ Tech Pack successfully generated via Inference API."
67
+
68
+ except Exception as e:
69
+ return None, f"❌ API Error: {str(e)}. (Check if your token has access to FLUX)"
70
 
71
  # --- GRADIO INTERFACE ---
72
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
73
+ gr.Markdown("# 👔 AI Tech-Pack Studio (CPU Optimized)")
74
+ gr.Markdown("Uses FLUX.1-schnell API to generate professional sketches without crashing the CPU.")
75
 
76
  with gr.Row():
77
+ with gr.Column():
78
+ with gr.Row():
79
+ f_in = gr.Image(label="Reference Front Photo", type="filepath")
80
+ b_in = gr.Image(label="Reference Back Photo", type="filepath")
81
+
82
+ g_type = gr.Dropdown(
83
+ ["T-Shirt", "Dress Shirt", "Hoodie", "Polo", "Jacket"],
84
+ value="T-Shirt",
85
+ label="Garment Type"
86
+ )
87
+ prompt = gr.Textbox(
88
+ label="Technical Details",
89
+ placeholder="e.g., Slim fit, dropped shoulders, rib-knit collar..."
90
+ )
91
  submit_btn = gr.Button("🚀 Generate Tech Pack", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
+ with gr.Column():
94
+ output_display = gr.Image(label="Final Combined Tech-Pack", type="pil")
95
+ status_logs = gr.Textbox(label="System Status")
96
 
97
  submit_btn.click(
98
+ fn=generate_tech_pack,
99
+ inputs=[f_in, b_in, prompt, g_type],
100
+ outputs=[output_display, status_logs]
101
  )
102
 
103
+ demo.launch()