-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
209 lines (178 loc) Β· 7.21 KB
/
Copy pathapp.py
File metadata and controls
209 lines (178 loc) Β· 7.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import streamlit as st
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import io
from PIL import Image
import zipfile # Add this import
def generate_synthetic_data(generator, num_samples=1000, latent_dim=128):
noise = tf.random.normal([num_samples, latent_dim])
generated_images = generator(noise, training=False)
generated_images = ((generated_images + 1) * 127.5).numpy().astype('uint8')
return generated_images
def plot_generated_images(images):
num_images = len(images)
cols = min(5, num_images)
rows = (num_images - 1) // cols + 1
plt.figure(figsize=(15, 3 * rows))
for i in range(num_images):
plt.subplot(rows, cols, i + 1)
plt.imshow(images[i, :, :, 0], cmap='gray')
plt.axis('off')
plt.tight_layout()
buf = io.BytesIO()
plt.savefig(buf, format='png')
plt.close()
buf.seek(0)
return buf
def analyze_generated_images(images):
return {
"Total Images": len(images),
"Mean Pixel Value": np.mean(images),
"Pixel Value Std Dev": np.std(images),
"Min Pixel Value": np.min(images),
"Max Pixel Value": np.max(images)
}
def load_generator_model():
return tf.keras.models.load_model("models/generator.keras", compile=False)
def images_to_zip(images):
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
for idx, img in enumerate(images):
pil_img = Image.fromarray(img[:, :, 0], mode="L")
img_bytes = io.BytesIO()
pil_img.save(img_bytes, format="PNG")
img_bytes.seek(0)
zf.writestr(f"digit_{idx+1}.png", img_bytes.read())
buf.seek(0)
return buf
def main():
st.set_page_config(
page_title="SynthDigit: MNIST GAN Generator",
page_icon="π€",
layout="wide",
initial_sidebar_state="expanded",
)
hide_streamlit_style = """
<style>
#MainMenu {visibility: hidden;} /* Hides the main menu */
footer {visibility: hidden;} /* Hides the footer */
header {visibility: hidden;} /* Hides the header */
.css-1d391kg {visibility: hidden;} /* Hides the status indicator */
.css-1v3fvcr {visibility: hidden;} /* Hides the Streamlit watermark */
.css-1v0mbdj {visibility: hidden;} /* Hides the overall container */
</style>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
st.markdown("""
<style>
.big-font {
font-size:20px !important;
font-weight: bold;
color: #2C3E50;
}
.sidebar .sidebar-content {
background-color: #F0F2F6;
}
</style>
""", unsafe_allow_html=True)
st.title("π€ SynthDigit: MNIST Digit Generator")
st.markdown("""
### Synthetic Digit Generation using Deep Convolutional Generative Adversarial Network
Generate realistic handwritten digits using advanced machine learning techniques.
""")
image = Image.open("images/banner.png")
st.image(image, caption="Sample Generated Images")
# Initialize session state for generator
if 'generator' not in st.session_state:
st.session_state.generator = None
st.markdown("---")
st.header("Image Generation")
st.sidebar.header("π οΈ Model Configuration")
# Dynamically show load button only if model is not loaded
if st.session_state.generator is None:
if st.sidebar.button("π Initialize GAN Generator"):
try:
st.session_state.generator = load_generator_model()
st.rerun() # Rerun to update the sidebar
except Exception as e:
st.sidebar.error(f"π¨ Model Initialization Failed: {e}")
else:
#Optional unload button if you want to reset
if st.sidebar.button("π Unload Model"):
st.session_state.generator = None
st.rerun()
st.sidebar.markdown("<br>", unsafe_allow_html=True) # Adds two line breaks
num_images = st.sidebar.slider(
"Number of Images to Generate",
min_value=1,
max_value=1000,
value=10
)
# Placeholders for generated images and zip buffer
generated_images = None
zip_buffer = None
if st.button("Generate Synthetic Digits"):
if st.session_state.generator is not None:
try:
images = generate_synthetic_data(
st.session_state.generator,
num_images
)
generated_images = images # Save for download
st.subheader("Generated Digits")
image_buffer = plot_generated_images(images)
st.image(image_buffer)
st.subheader("Image Analysis")
stats = analyze_generated_images(images)
col1, col2, col3, col4, col5 = st.columns(5)
with col1:
for key, value in list(stats.items())[:1]:
st.metric(key, f"{int(value)}")
with col2:
for key, value in list(stats.items())[1:2]:
st.metric(key, f"{value:.2f}")
with col3:
for key, value in list(stats.items())[2:3]:
st.metric(key, f"{value:.2f}")
with col4:
for key, value in list(stats.items())[3:4]:
st.metric(key, f"{value:.2f}")
with col5:
for key, value in list(stats.items())[4:]:
st.metric(key, f"{value:.2f}")
# Prepare ZIP for download
zip_buffer = images_to_zip(images)
st.session_state.generated_images_zip = zip_buffer.getvalue()
st.session_state.generated_images_ready = True
except Exception as e:
st.error(f"Error Generating Images: {e}")
st.session_state.generated_images_ready = False
else:
st.warning("Please load the model first!")
st.session_state.generated_images_ready = False
# Sidebar: Download button above About section
if st.session_state.get("generated_images_ready", False):
st.sidebar.download_button(
label="β¬οΈ Download Images (ZIP)",
data=st.session_state.generated_images_zip,
file_name="synthetic_digits.zip",
mime="application/zip"
)
st.sidebar.header("π About SynthDigit")
st.sidebar.info("""
SynthDigit is a Deep Convolutional GAN for generating synthetic MNIST digits.
Key Features:
- High-quality digit generation
- Configurable latent space
- Advanced machine learning techniques
- Downloadable synthetic images
""")
with st.sidebar.expander("π‘ **Potential Applications**"):
st.markdown("""
**1. Data Augmentation:** Increase training dataset size for digit recognition models.
**2. Anomaly Detection:** Generate diverse synthetic data to improve model robustness.
**3. Machine Learning Research:** Study generative model behavior.
**4. Educational Tool:** Demonstrate generative adversarial network principles.
""")
main()