ZainMalik0925 commited on
Commit
1a72794
1 Parent(s): 0138119

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -62
app.py CHANGED
@@ -1,78 +1,88 @@
1
  import streamlit as st
2
  from PIL import Image
3
- import requests
4
  from io import BytesIO
5
- import os
6
 
7
- # Title and Description
8
- st.title("Denim Virtual Try-On")
9
- st.write("Upload your leg image and the front image of denim pants to see how they fit.")
 
 
 
10
 
11
- # File Upload Section
12
- st.sidebar.header("Upload Images")
13
- subject_image = st.sidebar.file_uploader("Upload Subject Image (Legs)", type=["jpg", "jpeg", "png"])
14
- pant_front_image = st.sidebar.file_uploader("Upload Denim Pant Front Image", type=["jpg", "jpeg", "png"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- # Function to resize images to a manageable size
17
- def resize_image(image, max_size=(512, 512)):
18
- """Resize the image to a max size to reduce payload."""
19
- img = Image.open(image)
20
- img = img.convert("RGB") # Ensure image is in RGB format
21
- img.thumbnail(max_size) # Resize while maintaining aspect ratio
22
- byte_arr = BytesIO()
23
- img.save(byte_arr, format="JPEG") # Save to BytesIO in JPEG format
24
- byte_arr.seek(0)
25
- return byte_arr
26
 
27
- # Function to process images using Hugging Face API
28
- def virtual_tryon(subject_img, front_img):
29
- url = "https://api-inference.huggingface.co/models/ramim36/Kolors-Virtual-Try-On"
30
- headers = {"Authorization": f"Bearer {os.getenv('HF_API_TOKEN')}"}
31
 
32
- # Resize images before sending
33
- resized_subject = resize_image(subject_img)
34
- resized_front = resize_image(front_img)
 
 
35
 
36
- # Prepare data
37
- files = {
38
- "subject_image": ("subject.jpg", resized_subject, "image/jpeg"),
39
- "front_image": ("front.jpg", resized_front, "image/jpeg")
40
- }
41
 
42
- response = requests.post(url, headers=headers, files=files)
43
- if response.status_code == 200:
44
- return Image.open(BytesIO(response.content))
45
- else:
46
- st.error(f"Error: {response.status_code} - {response.text}")
47
- return None
48
 
49
- # Image Rotation Function
50
- def rotate_image(image, rotation_angle):
51
- """Rotate the uploaded image by the specified angle."""
52
- img = Image.open(image)
53
- return img.rotate(rotation_angle, expand=True)
 
54
 
55
- # Display Input Images and Add Rotation Option
56
- if subject_image:
57
- st.image(subject_image, caption="Uploaded Subject Image", use_column_width=True)
 
58
 
59
- if pant_front_image:
60
- rotation_angle = st.sidebar.slider("Rotate Front Denim Image", -180, 180, 0)
61
- rotated_front_image = rotate_image(pant_front_image, rotation_angle)
62
- st.image(rotated_front_image, caption="Rotated Front Denim Image", use_column_width=True)
63
- pant_front_image = BytesIO()
64
- rotated_front_image.save(pant_front_image, format="JPEG")
65
- pant_front_image.seek(0)
66
 
67
- # Generate Try-On Output
68
- if st.button("Generate Virtual Try-On"):
69
- if subject_image and pant_front_image:
70
- with st.spinner("Processing... Please wait."):
71
  try:
72
- composite_image = virtual_tryon(subject_image, pant_front_image)
73
- if composite_image:
74
- st.image(composite_image, caption="Virtual Try-On Result", use_column_width=True)
 
 
 
 
 
 
75
  except Exception as e:
76
- st.error(f"An error occurred: {e}")
77
- else:
78
- st.error("Please upload all required images.")
 
 
 
 
 
1
  import streamlit as st
2
  from PIL import Image
 
3
  from io import BytesIO
4
+ from transformers import pipeline
5
 
6
+ # Title and App Description
7
+ st.title("👗 Virtual Dress Try-On")
8
+ st.write("""
9
+ Upload a **Human Body Image** and a **Garment Image** to generate a Virtual Try-On.
10
+ Images will be compressed to meet Hugging Face size constraints.
11
+ """)
12
 
13
+ # Function to load and compress images
14
+ def compress_image(image_file, max_size_kb=512):
15
+ """
16
+ Compresses the input image to meet size constraints while preserving the aspect ratio.
17
+ Args:
18
+ image_file: Uploaded file from Streamlit
19
+ max_size_kb: Maximum file size in kilobytes
20
+ Returns:
21
+ Compressed PIL Image object
22
+ """
23
+ img = Image.open(image_file).convert("RGB")
24
+ quality = 95 # Initial compression quality
25
+ img_format = "JPEG"
26
+
27
+ # Compress image iteratively until it meets size constraints
28
+ while True:
29
+ img_bytes = BytesIO()
30
+ img.save(img_bytes, format=img_format, quality=quality)
31
+ size_kb = len(img_bytes.getvalue()) / 1024 # Size in KB
32
 
33
+ if size_kb <= max_size_kb or quality <= 10:
34
+ break
35
+ quality -= 5 # Reduce quality to compress further
 
 
 
 
 
 
 
36
 
37
+ compressed_img = Image.open(img_bytes)
38
+ return compressed_img
 
 
39
 
40
+ # Load Model (Hugging Face Pipeline)
41
+ @st.cache_resource
42
+ def load_model():
43
+ model_pipeline = pipeline("image-to-image", model="ares1123/virtual-dress-try-on")
44
+ return model_pipeline
45
 
46
+ model = load_model()
 
 
 
 
47
 
48
+ # Sidebar for Image Upload
49
+ st.sidebar.header("Upload Images")
50
+ uploaded_person = st.sidebar.file_uploader("Upload Human Body Image", type=["jpg", "jpeg", "png"])
51
+ uploaded_clothing = st.sidebar.file_uploader("Upload Garment Image", type=["jpg", "jpeg", "png"])
 
 
52
 
53
+ # Process and Display Images
54
+ if uploaded_person and uploaded_clothing:
55
+ # Compress uploaded images
56
+ st.sidebar.info("Compressing images to meet size constraints...")
57
+ person_image = compress_image(uploaded_person)
58
+ garment_image = compress_image(uploaded_clothing)
59
 
60
+ # Display compressed images
61
+ col1, col2 = st.columns(2)
62
+ col1.subheader("Compressed Human Body Image")
63
+ col1.image(person_image, use_column_width=True)
64
 
65
+ col2.subheader("Compressed Garment Image")
66
+ col2.image(garment_image, use_column_width=True)
 
 
 
 
 
67
 
68
+ # Process button
69
+ if st.button("👗 Generate Virtual Try-On"):
70
+ with st.spinner("Processing images... Please wait ⏳"):
 
71
  try:
72
+ # Prepare inputs for the model
73
+ inputs = {"image": person_image, "clothing": garment_image}
74
+
75
+ # Generate output using Hugging Face model
76
+ output_image = model(inputs)
77
+
78
+ # Display output image
79
+ st.subheader("✨ Virtual Try-On Result")
80
+ st.image(output_image, use_column_width=True, caption="Composite Virtual Try-On Image")
81
  except Exception as e:
82
+ st.error(f"An error occurred during processing: {e}")
83
+ else:
84
+ st.warning("Please upload both the Human Body Image and Garment Image.")
85
+
86
+ # Footer
87
+ st.markdown("---")
88
+ st.write("Developed with ❤️ using Streamlit and Hugging Face.")