Adeel020 commited on
Commit
f8cd3a4
·
verified ·
1 Parent(s): 52516d1

Delete app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +0 -141
app.py DELETED
@@ -1,141 +0,0 @@
1
- """IVM — Image + Video + Model. v1.0.0"""
2
- import gradio as gr
3
- from PIL import Image, ImageFilter
4
- import uuid, os, json, time, requests, subprocess
5
- from pathlib import Path
6
-
7
- OUT = Path("/tmp/ivm_output"); OUT.mkdir(exist_ok=True)
8
- HIST = Path("/tmp/ivm_history.json")
9
-
10
- def save_h(**kw):
11
- h = json.loads(HIST.read_text()) if HIST.exists() else []
12
- h.insert(0, {"time": time.strftime("%Y-%m-%d %H:%M"), **kw})
13
- HIST.write_text(json.dumps(h[:30]))
14
-
15
- def load_h():
16
- return json.loads(HIST.read_text()) if HIST.exists() else []
17
-
18
- def composite(dress, model):
19
- """Composite dress onto model using PIL only."""
20
- d = Image.open(dress).convert("RGBA").resize((512, 512))
21
- m = Image.open(model).convert("RGBA").resize((512, 512)) if model else Image.new("RGBA", (512, 512), (245, 240, 235, 255))
22
-
23
- # Create a mask from the dress - remove white/light background
24
- # Convert dress to grayscale and threshold
25
- gray = d.convert("L")
26
- mask = gray.point(lambda x: 0 if x > 230 else 255)
27
- mask = mask.filter(ImageFilter.MinFilter(3))
28
- mask = mask.filter(ImageFilter.SmoothFilter())
29
-
30
- # Resize dress to fit on model body
31
- d_resized = d.copy()
32
-
33
- # Composite: paste dress onto model using mask
34
- result = m.copy()
35
- # Center the dress on the model body
36
- x = (m.width - d_resized.width) // 2
37
- y = int(m.height * 0.12)
38
- result.paste(d_resized, (x, y), mask)
39
-
40
- # Convert back to RGB and crop top 30% to hide face
41
- result = result.convert("RGB")
42
- w, h = result.size
43
- result = result.crop((0, int(h * 0.30), w, h))
44
-
45
- out = str(OUT / f"ivm_{uuid.uuid4().hex[:8]}.png")
46
- result.save(out)
47
- save_h(image_path=out)
48
- return out
49
-
50
-
51
- def generate_video(image_path):
52
- """Generate looping video from IVM image using Stable Video Diffusion."""
53
- if not image_path or not os.path.isfile(image_path):
54
- raise gr.Error("Generate an IVM image first")
55
-
56
- svd_url = "https://stabilityai-stable-video-diffusion-img2vid.hf.space"
57
-
58
- with open(image_path, "rb") as f:
59
- upload = requests.post(f"{svd_url}/upload", files={"files": f}, timeout=60)
60
- if upload.status_code != 200:
61
- raise gr.Error("Video service unavailable")
62
-
63
- file_hash = upload.json()[0]
64
-
65
- resp = requests.post(f"{svd_url}/api/predict", json={
66
- "data": [{"path": f"/tmp/{file_hash}"}, "Auto", 25, -1, 2.5, "SVD"],
67
- "event_data": None, "fn_index": 0,
68
- }, timeout=300)
69
-
70
- if resp.status_code == 200:
71
- data = resp.json().get("data", [])
72
- if data and isinstance(data[0], dict) and data[0].get("path"):
73
- video_path = str(OUT / f"vid_{uuid.uuid4().hex[:8]}.mp4")
74
- vid_resp = requests.get(f"{svd_url}/file={data[0]['path']}", timeout=120)
75
- with open(video_path, "wb") as f:
76
- f.write(vid_resp.content)
77
-
78
- cropped = str(OUT / f"vid_{uuid.uuid4().hex[:8]}_body.mp4")
79
- subprocess.run(
80
- ["ffmpeg", "-i", video_path, "-vf", "crop=iw:ih*0.7:0:ih*0.3", cropped],
81
- capture_output=True, timeout=30
82
- )
83
- return cropped if os.path.isfile(cropped) else video_path
84
-
85
- raise gr.Error("Video generation failed")
86
-
87
-
88
- def history_html():
89
- data = load_h()
90
- if not data:
91
- return "<p style='color:#666;text-align:center;padding:30px'>No images generated yet</p>"
92
- cards = []
93
- for h in data:
94
- ip = h.get("image_path", "")
95
- cards.append(
96
- "<div style='background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06);"
97
- "border-radius:10px;padding:10px;margin-bottom:8px'>"
98
- f"<img src='/file={ip}' style='width:100%;height:150px;object-fit:contain;"
99
- "border-radius:6px;background:#000;margin-bottom:6px'/>"
100
- f"<div style='display:flex;justify-content:space-between;align-items:center'>"
101
- f"<span style='font-size:10px;color:#666'>{h.get('time','')}</span>"
102
- f"<a href='/file={ip}' download style='font-size:11px;color:#a855f7;font-weight:600'>⬇ Download</a>"
103
- "</div></div>"
104
- )
105
- return "".join(cards)
106
-
107
-
108
- CSS = """
109
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap');
110
- *{font-family:'Inter',sans-serif}
111
- body{background:#0a0a0f!important}
112
- .gradio-container{max-width:1100px!important;margin:auto;background:transparent!important}
113
- footer{display:none!important}
114
- .gr-box,.gr-form{border-radius:14px!important;border:1px solid rgba(255,255,255,0.06)!important;background:rgba(17,17,24,0.9)!important}
115
- input,textarea,select{background:rgba(22,22,31,0.9)!important;border:1px solid rgba(255,255,255,0.08)!important;border-radius:10px!important;color:#f1f1f5!important}
116
- .gr-button-primary{background:linear-gradient(135deg,#a855f7,#7c3aed)!important;border:none!important;border-radius:10px!important;color:#fff!important;font-weight:600!important}
117
- .gradio-container h1{font-size:2.8em!important;font-weight:900!important;background:linear-gradient(135deg,#a855f7,#06b6d4)!important;-webkit-background-clip:text!important;-webkit-text-fill-color:transparent!important}
118
- """
119
-
120
- with gr.Blocks(title="IVM Studio", css=CSS) as demo:
121
- gr.Markdown("# IVM Studio\nAI Dress-on-Model · Upload a dress photo, AI puts it on a model")
122
-
123
- with gr.Row():
124
- with gr.Column(scale=1):
125
- dress = gr.Image(label="Dress Photo", type="filepath", sources=["upload"])
126
- model = gr.Image(label="Model Photo (optional)", type="filepath", sources=["upload"])
127
- btn = gr.Button("Generate IVM Image", variant="primary", size="lg")
128
- with gr.Column(scale=1):
129
- result_img = gr.Image(label="Result (Body Only)", type="filepath")
130
- result_vid = gr.Video(label="Looping Video")
131
- vid_btn = gr.Button("Generate Video", size="sm")
132
-
133
- btn.click(fn=composite, inputs=[dress, model], outputs=[result_img], api_name="gen")
134
- vid_btn.click(fn=generate_video, inputs=[result_img], outputs=[result_vid], api_name="vid")
135
-
136
- gr.Markdown("### Previously Generated")
137
- hist = gr.HTML(value=history_html())
138
- gr.Button("Refresh").click(fn=history_html, outputs=hist, api_name="refresh")
139
-
140
- if __name__ == "__main__":
141
- demo.launch(server_name="0.0.0.0", server_port=7860, share=False)