muhammadnoman76 commited on
Commit
17ca604
·
1 Parent(s): 265fd75
67abc821-35b0-45ae-9169-bb5492df4a45.png ADDED

Git LFS Details

  • SHA256: d664e1a68febc481e1525fe1be7f6bb8f402946be7c0aefd90034acf07c10cdc
  • Pointer size: 131 Bytes
  • Size of remote file: 105 kB
app.py CHANGED
@@ -1,146 +1,29 @@
1
- # must come before any st.* calls
2
- from streamlit.web.server.health import HealthHandler
3
-
4
- def patched_get(self):
5
- # force a JSON response
6
- self.write({"status": "ok"})
7
-
8
- HealthHandler.get = patched_get
9
-
10
-
11
- import streamlit as st
12
  import cv2
13
- import numpy as np
14
- from PIL import Image
15
- import os
16
  from modelscope.pipelines import pipeline
17
  from modelscope.utils.constant import Tasks
18
- from huggingface_hub import snapshot_download
19
- import io
20
- import sys
21
- import asyncio
22
- import shutil
23
 
24
- # Fix for Python 3.12 asyncio issue
25
- if sys.version_info >= (3, 12) and sys.platform.startswith('win'):
26
- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
27
 
28
- def main():
29
- st.set_page_config(page_title="Image Colorization", layout="wide")
30
- st.title("Black & White to Color Image Converter")
31
-
32
- # Create examples directory if it doesn't exist
33
- examples_dir = "./examples"
34
- if not os.path.exists(examples_dir):
35
- os.makedirs(examples_dir)
36
-
37
- example_images = ["image1.jpg", "image2.jpg", "image3.jpg"]
38
- for img in example_images:
39
- if os.path.exists(img):
40
- shutil.copy(img, os.path.join(examples_dir, img))
41
-
42
- # Check if model is already downloaded
43
- model_dir = "./makeitcolor"
44
- if not os.path.exists(model_dir):
45
- with st.spinner("Downloading model (this might take a few minutes)..."):
46
- snapshot_download(repo_id="muhammadnoman76/makeitcolor", local_dir=model_dir, repo_type="model")
47
-
48
- # Initialize the colorization pipeline
49
- try:
50
- img_colorization = pipeline(Tasks.image_colorization, model=model_dir)
51
- st.success("Model loaded successfully!")
52
- except Exception as e:
53
- st.error(f"Failed to load model: {e}")
54
- return
55
-
56
- # Example images section
57
- st.subheader("Try with Example Images")
58
- example_col1, example_col2, example_col3 = st.columns(3)
59
 
60
- with example_col1:
61
- if os.path.exists(os.path.join(examples_dir, "image1.jpg")):
62
- st.image(os.path.join(examples_dir, "image1.jpg"), caption="Example 1", use_container_width=True)
63
- if st.button("Colorize Example 1"):
64
- process_image(os.path.join(examples_dir, "image1.jpg"), img_colorization)
65
-
66
- with example_col2:
67
- if os.path.exists(os.path.join(examples_dir, "image2.jpg")):
68
- st.image(os.path.join(examples_dir, "image2.jpg"), caption="Example 2", use_container_width=True)
69
- if st.button("Colorize Example 2"):
70
- process_image(os.path.join(examples_dir, "image2.jpg"), img_colorization)
71
-
72
- with example_col3:
73
- if os.path.exists(os.path.join(examples_dir, "image3.jpg")):
74
- st.image(os.path.join(examples_dir, "image3.jpg"), caption="Example 3", use_container_width=True)
75
- if st.button("Colorize Example 3"):
76
- process_image(os.path.join(examples_dir, "image3.jpg"), img_colorization)
77
-
78
- st.markdown("---")
79
- st.subheader("Upload Your Own Image")
80
-
81
- # File uploader
82
- uploaded_file = st.file_uploader("Upload a black and white image", type=["jpg", "jpeg", "png"])
83
-
84
- if uploaded_file is not None:
85
- # Read and display the original image
86
- original_image = Image.open(uploaded_file)
87
-
88
- # Create temporary file path for processing
89
- temp_path = "temp_input.jpg"
90
- original_image.save(temp_path)
91
-
92
- process_image(temp_path, img_colorization)
93
-
94
- # Clean up temp file
95
- if os.path.exists(temp_path):
96
- os.remove(temp_path)
97
 
98
- def process_image(image_path, img_colorization):
99
- # Display original image
100
- original_image = Image.open(image_path)
101
-
102
- col1, col2 = st.columns(2)
103
-
104
- with col1:
105
- st.subheader("Original Image")
106
- st.image(original_image, use_container_width=True)
107
-
108
- # Colorize the image
109
- try:
110
- with st.spinner("Colorizing image..."):
111
- result = img_colorization(image_path)
112
- colorized_image = result['output_img']
113
-
114
- # Convert BGR to RGB for display
115
- colorized_image_rgb = cv2.cvtColor(colorized_image, cv2.COLOR_BGR2RGB)
116
-
117
- with col2:
118
- st.subheader("Colorized Image")
119
- st.image(colorized_image_rgb, use_container_width=True)
120
-
121
- # Add download button for colorized image
122
- colorized_pil = Image.fromarray(colorized_image_rgb)
123
- buf = io.BytesIO()
124
- colorized_pil.save(buf, format="PNG")
125
- byte_im = buf.getvalue()
126
-
127
- st.download_button(
128
- label="Download Colorized Image",
129
- data=byte_im,
130
- file_name="colorized_image.png",
131
- mime="image/png"
132
- )
133
- except Exception as e:
134
- st.error(f"Error during colorization: {e}")
135
 
 
136
 
137
  if __name__ == "__main__":
138
- main()
139
-
140
- st.markdown("---")
141
- st.markdown("""
142
- <div style="text-align: center; padding: 10px; background-color: #f0f2f6; border-radius: 5px;">
143
- <p>Developed by <a href="https://www.linkedin.com/in/muhammad-noman76/" target="_blank">Muhammad Noman</a> |
144
- Contact: muhammadnomanshafiq76@gmail.com</p>
145
- </div>
146
- """, unsafe_allow_html=True)
 
1
+ import gradio as gr
 
 
 
 
 
 
 
 
 
 
2
  import cv2
3
+ from modelscope.outputs import OutputKeys
 
 
4
  from modelscope.pipelines import pipeline
5
  from modelscope.utils.constant import Tasks
6
+ import numpy as np
7
+ import uuid
8
+ from gradio_imageslider import ImageSlider
 
 
9
 
10
+ img_colorization = pipeline(Tasks.image_colorization, model='./makeitcolor')
11
+ img_path = 'input.png'
 
12
 
13
+ def color(image):
14
+ output = img_colorization(image[...,::-1])
15
+ result = output[OutputKeys.OUTPUT_IMG].astype(np.uint8)
16
+ unique_imgfilename = str(uuid.uuid4()) + '.png'
17
+ cv2.imwrite(unique_imgfilename, result)
18
+ print('infer finished!')
19
+ return (image, unique_imgfilename)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ title = "old_photo_restoration"
23
+ description = "upload old photo, ddcolor image colorization"
24
+ examples = [['examples/image1.jpg' , 'examples/image2.jpg' , 'examples/image3.jpg'],]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ demo = gr.Interface(fn=color,inputs="image",outputs=ImageSlider(position=0.5,label='Colored image with slider-view'),examples=examples,title=title,description=description)
27
 
28
  if __name__ == "__main__":
29
+ demo.launch(share=False)
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,5 +1,6 @@
1
  timm
2
- streamlit>=1.24.0
 
3
  opencv-python>=4.7.0
4
  modelscope==1.12.0
5
  datasets==2.14.7
 
1
  timm
2
+ gradio
3
+ gradio_imageslider
4
  opencv-python>=4.7.0
5
  modelscope==1.12.0
6
  datasets==2.14.7