Update pages/3_Sketch_To_Image.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184import streamlit as stimport osimport gdownfrom PIL import Imageimport torchfrom facenet_pytorch import MTCNNimport matplotlib.pyplot as pltfrom generator import UNetGeneratorfrom utils import generate_image_from_sketch# --- Setup ---os.environ["STREAMLIT_SERVER_FILE_WATCHER_TYPE"] = "none"model_url = "https://drive.google.com/uc?id=1cyI-A-D1PLcTW3nKH6RmkNLPUNefHJk0"model_path = "pix2pix_generator.pth"face_area_threshold = 0.25# --- Load Generator ---@st.cache_resource(show_spinner="Loading Generator...")def load_generator():if not os.path.exists(model_path):gdown.download(model_url, model_path, quiet=False, fuzzy=True)print("β Pix2Pix Model Downloaded!")else:print("βΉοΈ Model already exists.")model = UNetGenerator()state_dict = torch.load(model_path, map_location=torch.device("cpu"))model.load_state_dict(state_dict)model.eval()return model# --- Load Face Detector ---@st.cache_resource()def load_mtcnn():device = 'cuda' if torch.cuda.is_available() else 'cpu'return MTCNN(keep_all=True, device=device)generator = load_generator()mtcnn = load_mtcnn()# --- UI ---st.title("π¨ Sketch to Image + Face Detection")uploaded = st.file_uploader("Upload a Sketch", type=["jpg", "jpeg", "png"])if uploaded:image = Image.open(uploaded).convert("RGB")fixed_size = (784, 784)image = image.resize(fixed_size)# --- Face Detection ---boxes, _ = mtcnn.detect(image)width, height = image.sizeimage_area = width * heightface_count = 0face_ratio = 0if boxes is not None and len(boxes) > 0:face_count = len(boxes)face_areas = [(box[2] - box[0]) * (box[3] - box[1]) for box in boxes]max_face_area = max(face_areas)face_ratio = max_face_area / image_areaelse:st.warning("β No face detected in the sketch.")# --- Output Info ---st.write(f"π§ Faces Detected: **{face_count}**")st.write(f"π Largest Face Covers: **{face_ratio*100:.2f}%**")# --- Show Input Image with Boxes ---st.subheader("Sketch with Face Detection")fig, ax = plt.subplots()ax.imshow(image)if boxes is not None:for box in boxes:x1, y1, x2, y2 = boxrect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1,fill=False, color='red', linewidth=2)ax.add_patch(rect)plt.axis('off')st.pyplot(fig)# --- Show Results ---col1, col2 = st.columns(2)with col1:st.subheader("Sketch Input")st.image(image, width=fixed_size[0])with col2:st.subheader("Generated Image")if face_count == 1 and face_ratio >= face_area_threshold:generated_image = generate_image_from_sketch(image, generator)generated_image = generated_image.resize(fixed_size)st.image(generated_image, width=fixed_size[0])else:st.warning("β Pix2Pix model not applied. Either no face or multiple faces detected, or face is too small.")# import streamlit as st# import os# import torch# from PIL import Image# import matplotlib.pyplot as plt# from facenet_pytorch import MTCNN# from generator import UNetGenerator# from utils import generate_image_from_sketch# from image_search import query_custom_model, update_custom_image_paths# from download import download_flickr8k_dataset # β Your helper function# # Constants# MODEL_PATH = "pix2pix_generator.pth"# MODEL_FILE_ID = "1cyI-A-D1PLcTW3nKH6RmkNLPUNefHJk0"# DATASET_DIR = "flickr8k_dataset"# FACE_AREA_THRESHOLD = 0.25# device = "cuda" if torch.cuda.is_available() else "cpu"# mtcnn = MTCNN(keep_all=True, device=device)# # --- Download model ---# @st.cache_resource(show_spinner="Loading Generator...")# def load_generator():# import gdown# if not os.path.exists(MODEL_PATH):# url = f"https://drive.google.com/uc?id={MODEL_FILE_ID}"# gdown.download(url, MODEL_PATH, quiet=False, fuzzy=True)# model = UNetGenerator()# state_dict = torch.load(MODEL_PATH, map_location=torch.device("cpu"))# model.load_state_dict(state_dict)# model.eval()# return model# # --- Download dataset ---# @st.cache_resource(show_spinner="Downloading Flickr8k dataset...")# def prepare_dataset():# download_flickr8k_dataset(DATASET_DIR) # β Use your existing function# update_custom_image_paths(DATASET_DIR) # β Make sure image_search.py reads from correct path# # --- Face Detection ---# def detect_faces_and_ratio(image):# width, height = image.size# image_area = width * height# boxes, _ = mtcnn.detect(image)# if boxes is None:# return 0, 0.0, None# face_areas = [(box[2] - box[0]) * (box[3] - box[1]) for box in boxes]# max_face_area = max(face_areas)# ratio = max_face_area / image_area# return len(boxes), ratio, boxes# # --- Initialize ---# generator = load_generator()# prepare_dataset()# # --- Streamlit UI ---# st.title("π¨ Sketch to Image or Retrieval")# uploaded = st.file_uploader("Upload a Sketch", type=["jpg", "jpeg", "png"])# if uploaded:# image = Image.open(uploaded).convert("RGB").resize((784, 784))# num_faces, face_ratio, _ = detect_faces_and_ratio(image)# st.markdown(f"β Detected **{num_faces} face(s)**. Largest face covers **{face_ratio*100:.2f}%** of the image.")# if num_faces == 1 and face_ratio >= FACE_AREA_THRESHOLD:# st.subheader("π§ Passed Face Check - Using Pix2Pix")# generated = generate_image_from_sketch(image, generator).resize((784, 784))# col1, col2 = st.columns(2)# with col1:# st.subheader("Sketch Input")# st.image(image)# with col2:# st.subheader("Generated Image")# st.image(generated)# else:# st.subheader("π· Pix2Pix Skipped - Showing Similar Images")# top_paths = query_custom_model(image=image, k=5)# top_images = [Image.open(p).resize((220, 220)) for p in top_paths]# st.image(top_images, width=220, caption=[f"Rank {i+1}" for i in range(len(top_images))])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276# import streamlit as st# import os# import gdown# from PIL import Image# import torch# from facenet_pytorch import MTCNN# import matplotlib.pyplot as plt# from generator import UNetGenerator# from utils import generate_image_from_sketch# # --- Setup ---# os.environ["STREAMLIT_SERVER_FILE_WATCHER_TYPE"] = "none"# model_url = "https://drive.google.com/uc?id=1cyI-A-D1PLcTW3nKH6RmkNLPUNefHJk0"# model_path = "pix2pix_generator.pth"# face_area_threshold = 0.25# # --- Load Generator ---# @st.cache_resource(show_spinner="Loading Generator...")# def load_generator():# if not os.path.exists(model_path):# gdown.download(model_url, model_path, quiet=False, fuzzy=True)# print("β Pix2Pix Model Downloaded!")# else:# print("βΉοΈ Model already exists.")# model = UNetGenerator()# state_dict = torch.load(model_path, map_location=torch.device("cpu"))# model.load_state_dict(state_dict)# model.eval()# return model# # --- Load Face Detector ---# @st.cache_resource()# def load_mtcnn():# device = 'cuda' if torch.cuda.is_available() else 'cpu'# return MTCNN(keep_all=True, device=device)# generator = load_generator()# mtcnn = load_mtcnn()# # --- UI ---# st.title("π¨ Sketch to Image + Face Detection")# uploaded = st.file_uploader("Upload a Sketch", type=["jpg", "jpeg", "png"])# if uploaded:# image = Image.open(uploaded).convert("RGB")# fixed_size = (784, 784)# image = image.resize(fixed_size)# # --- Face Detection ---# boxes, _ = mtcnn.detect(image)# width, height = image.size# image_area = width * height# face_count = 0# face_ratio = 0# if boxes is not None and len(boxes) > 0:# face_count = len(boxes)# face_areas = [(box[2] - box[0]) * (box[3] - box[1]) for box in boxes]# max_face_area = max(face_areas)# face_ratio = max_face_area / image_area# else:# st.warning("β No face detected in the sketch.")# # --- Output Info ---# st.write(f"π§ Faces Detected: **{face_count}**")# st.write(f"π Largest Face Covers: **{face_ratio*100:.2f}%**")# # --- Show Input Image with Boxes ---# st.subheader("Sketch with Face Detection")# fig, ax = plt.subplots()# ax.imshow(image)# if boxes is not None:# for box in boxes:# x1, y1, x2, y2 = box# rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1,# fill=False, color='red', linewidth=2)# ax.add_patch(rect)# plt.axis('off')# st.pyplot(fig)# # --- Show Results ---# col1, col2 = st.columns(2)# with col1:# st.subheader("Sketch Input")# st.image(image, width=fixed_size[0])# with col2:# st.subheader("Generated Image")# if face_count == 1 and face_ratio >= face_area_threshold:# generated_image = generate_image_from_sketch(image, generator)# generated_image = generated_image.resize(fixed_size)# st.image(generated_image, width=fixed_size[0])# else:# st.warning("β Pix2Pix model not applied. Either no face or multiple faces detected, or face is too small.")# # import streamlit as st# # import os# # import torch# # from PIL import Image# # import matplotlib.pyplot as plt# # from facenet_pytorch import MTCNN# # from generator import UNetGenerator# # from utils import generate_image_from_sketch# # from image_search import query_custom_model, update_custom_image_paths# # from download import download_flickr8k_dataset # β Your helper function# # # Constants# # MODEL_PATH = "pix2pix_generator.pth"# # MODEL_FILE_ID = "1cyI-A-D1PLcTW3nKH6RmkNLPUNefHJk0"# # DATASET_DIR = "flickr8k_dataset"# # FACE_AREA_THRESHOLD = 0.25# # device = "cuda" if torch.cuda.is_available() else "cpu"# # mtcnn = MTCNN(keep_all=True, device=device)# # # --- Download model ---# # @st.cache_resource(show_spinner="Loading Generator...")# # def load_generator():# # import gdown# # if not os.path.exists(MODEL_PATH):# # url = f"https://drive.google.com/uc?id={MODEL_FILE_ID}"# # gdown.download(url, MODEL_PATH, quiet=False, fuzzy=True)# # model = UNetGenerator()# # state_dict = torch.load(MODEL_PATH, map_location=torch.device("cpu"))# # model.load_state_dict(state_dict)# # model.eval()# # return model# # # --- Download dataset ---# # @st.cache_resource(show_spinner="Downloading Flickr8k dataset...")# # def prepare_dataset():# # download_flickr8k_dataset(DATASET_DIR) # β Use your existing function# # update_custom_image_paths(DATASET_DIR) # β Make sure image_search.py reads from correct path# # # --- Face Detection ---# # def detect_faces_and_ratio(image):# # width, height = image.size# # image_area = width * height# # boxes, _ = mtcnn.detect(image)# # if boxes is None:# # return 0, 0.0, None# # face_areas = [(box[2] - box[0]) * (box[3] - box[1]) for box in boxes]# # max_face_area = max(face_areas)# # ratio = max_face_area / image_area# # return len(boxes), ratio, boxes# # # --- Initialize ---# # generator = load_generator()# # prepare_dataset()# # # --- Streamlit UI ---# # st.title("π¨ Sketch to Image or Retrieval")# # uploaded = st.file_uploader("Upload a Sketch", type=["jpg", "jpeg", "png"])# # if uploaded:# # image = Image.open(uploaded).convert("RGB").resize((784, 784))# # num_faces, face_ratio, _ = detect_faces_and_ratio(image)# # st.markdown(f"β Detected **{num_faces} face(s)**. Largest face covers **{face_ratio*100:.2f}%** of the image.")# # if num_faces == 1 and face_ratio >= FACE_AREA_THRESHOLD:# # st.subheader("π§ Passed Face Check - Using Pix2Pix")# # generated = generate_image_from_sketch(image, generator).resize((784, 784))# # col1, col2 = st.columns(2)# # with col1:# # st.subheader("Sketch Input")# # st.image(image)# # with col2:# # st.subheader("Generated Image")# # st.image(generated)# # else:# # st.subheader("π· Pix2Pix Skipped - Showing Similar Images")# # top_paths = query_custom_model(image=image, k=5)# # top_images = [Image.open(p).resize((220, 220)) for p in top_paths]# # st.image(top_images, width=220, caption=[f"Rank {i+1}" for i in range(len(top_images))])import streamlit as stimport osfrom PIL import Imageimport torchfrom generator import UNetGeneratorfrom utils import generate_image_from_sketchfrom download import download_flickr8k_datasetfrom facenet_pytorch import MTCNNimport matplotlib.pyplot as pltfrom image_search import query_custom_model # your custom model logic# π Path settingsDATASET_DIR = "flickr8k/Flickr8k_Dataset"MODEL_PATH = "pix2pix_generator.pth"FILE_ID = "1cyI-A-D1PLcTW3nKH6RmkNLPUNefHJk0"MODEL_URL = f"https://drive.google.com/uc?id={FILE_ID}"# Face detection thresholdFACE_AREA_THRESHOLD = 0.25# Setup MTCNN for face detectiondevice = "cuda" if torch.cuda.is_available() else "cpu"mtcnn = MTCNN(keep_all=True, device=device)# Download and extract dataset@st.cache_resource(show_spinner="Preparing dataset...")def prepare_dataset():download_flickr8k_dataset()# Download model if not already present@st.cache_resource(show_spinner="Loading Pix2Pix Generator...")def load_generator():import gdownif not os.path.exists(MODEL_PATH):gdown.download(MODEL_URL, MODEL_PATH, quiet=False, fuzzy=True)model = UNetGenerator()state_dict = torch.load(MODEL_PATH, map_location=torch.device("cpu"))model.load_state_dict(state_dict)model.eval()return model# Face detection logicdef is_single_face_within_threshold(img: Image.Image, threshold=FACE_AREA_THRESHOLD, visualize=False):width, height = img.sizeimage_area = width * heightboxes, _ = mtcnn.detect(img)if boxes is None or len(boxes) != 1:return False, 0# Calculate face area ratiox1, y1, x2, y2 = boxes[0]face_area = (x2 - x1) * (y2 - y1)face_ratio = face_area / image_areaif visualize:plt.imshow(img)ax = plt.gca()rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1,fill=False, color='red', linewidth=2)ax.add_patch(rect)plt.axis('off')st.pyplot(plt)return face_ratio >= threshold, face_ratio# π Streamlit UIst.title("π¨ Sketch to Image")uploaded = st.file_uploader("Upload a Sketch", type=["jpg", "jpeg", "png"])if uploaded:prepare_dataset()generator = load_generator()sketch = Image.open(uploaded).convert("RGB")sketch = sketch.resize((784, 784))st.subheader("Sketch Preview")st.image(sketch, width=392)use_pix2pix, face_ratio = is_single_face_within_threshold(sketch, visualize=True)if use_pix2pix:st.success(f"β Detected one clear face (covering {face_ratio*100:.2f}%) β using Pix2Pix!")generated_image = generate_image_from_sketch(sketch, generator)st.subheader("Generated Image")st.image(generated_image.resize((784, 784)))else:st.warning(f"β οΈ Pix2Pix skipped (face count β 1 or face < {FACE_AREA_THRESHOLD*100:.0f}%). Showing similar images.")top_images = query_custom_model(image=sketch, k=5)st.subheader("Top 5 Similar Images (Custom Model)")st.image(top_images, width=150, caption=[f"Match {i+1}" for i in range(len(top_images))])
pages/3_Sketch_To_Image.py+249-157