import tensorflow as tf
from tensorflow import keras
import streamlit as st
import cv2
import numpy as np
import time
from PIL import Image
import plotly.graph_objects as go
from modules.enhance import enhancement_pipeline, detect_brightness
from modules.parallel import parallel_enhancement
from modules.metrics import calculate_execution_metrics, get_image_info
from modules.dataset_loader import get_lol_dataset_samples, load_lol_pair
import io
import os
import multiprocessing
from tensorflow.keras.models import load_model
model = load_model("lowlight_enhancer.keras")
# ---------------------------------------------------------
# UI CONFIGURATION
# ---------------------------------------------------------
st.set_page_config(
page_title="Parallel Low Light Image Enhancement",
page_icon="⚡",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for Professional Branding
st.markdown("""
""", unsafe_allow_html=True)
# ---------------------------------------------------------
# SIDEBAR CONTROLS
# ---------------------------------------------------------
st.sidebar.markdown("
⚡ PLL-SIE System
", unsafe_allow_html=True)
st.sidebar.caption("Parallel Low Light Smart Image Enhancement")
st.sidebar.markdown("---")
app_mode = st.sidebar.selectbox("Navigation", ["Image Workspace", "LOL Dataset Explorer", "Webcam Live", "Project Report"])
if app_mode != "Project Report":
st.sidebar.subheader("🎚️ Enhancement Params")
gamma_val = st.sidebar.slider("Gamma Correction", 0.5, 4.0, 1.8, 0.1)
clahe_clip = st.sidebar.slider("CLAHE Contrast", 1.0, 10.0, 3.0, 0.5)
denoise_h = st.sidebar.slider("Noise Reduction", 0, 30, 12, 1)
st.sidebar.markdown("---")
st.sidebar.subheader("⚙️ System Status")
cpu_count = multiprocessing.cpu_count()
st.sidebar.info(f"Available Logical Cores: {cpu_count}")
parallel_cores = st.sidebar.number_input("Cores to allocate", 1, cpu_count, max(1, cpu_count-1))
st.sidebar.markdown("---")
st.sidebar.markdown("### Development Info")
st.sidebar.write("v1.2.0-Production")
# ---------------------------------------------------------
# CORE LOGIC
# ---------------------------------------------------------
def run_image_enhancement(input_img):
config = {
"gamma_enable": True,
"gamma": gamma_val,
"clahe_enable": True,
"clahe_clip": clahe_clip,
"denoise_enable": True,
"denoise_h": denoise_h,
"sharpen_enable": True,
"cores": parallel_cores
}
results = calculate_execution_metrics(
enhancement_pipeline,
parallel_enhancement,
input_img,
config
)
return results
def main():
if app_mode == "Image Workspace":
st.header("📸 Image Enhancement Workspace")
uploaded_file = st.file_uploader("Select source image", type=['jpg', 'jpeg', 'png', 'tiff'], key="main_image_loader")
if uploaded_file:
img = Image.open(uploaded_file).convert("RGB")
img_np = np.array(img)
info = get_image_info(img_np)
brightness = detect_brightness(img_np)
# Metadata Dashboard
col_b1, col_b2, col_b3 = st.columns(3)
with col_b1:
st.metric("Mean Brightness", f"{brightness:.1f} cd/m²")
with col_b2:
st.metric("Total Pixels", f"{info['megapixels']:.2f} MP")
with col_b3:
status = "🔴 UNDEREXPOSED" if brightness < 70 else "🟢 OPTIMAL"
st.metric("System Auto-Diagnosis", status)
st.markdown("---")
if st.button("🚀 EXECUTE MULTIPROCESSING PIPELINE"):
with st.spinner("Synchronizing CPU workers..."):
metrics = run_image_enhancement(img_np)
# Visualization
c1, c2 = st.columns(2)
with c1:
st.subheader("Input Frame")
st.image(img_np, use_container_width=True)
with c2:
st.subheader("Enhanced Signal")
st.image(metrics['result'], use_container_width=True)
# Performance Graph
st.markdown("---")
st.subheader("📈 Throughput Analytics")
m1, m2, m3 = st.columns(3)
m1.metric("Sequential (ST)", f"{metrics['sequential_time']:.4f}s")
m2.metric("Parallel (MP)", f"{metrics['parallel_time']:.4f}s")
m3.metric("Efficiency Gain", f"{metrics['speedup']:.2f}x")
fig = go.Figure(data=[
go.Bar(name='Single-Thread', x=['Execution'], y=[metrics['sequential_time']], marker_color='#ff4b4b'),
go.Bar(name='Multi-Process', x=['Execution'], y=[metrics['parallel_time']], marker_color='#00d1ff')
])
fig.update_layout(template="plotly_dark", barmode='group', height=300)
st.plotly_chart(fig, use_container_width=True)
# Download
result_pil = Image.fromarray(metrics['result'])
buf = io.BytesIO()
result_pil.save(buf, format="PNG")
st.download_button(
label="💾 Export High-Fidelity Result",
data=buf.getvalue(),
file_name="enhanced_parallel_output.png",
mime="image/png"
)
elif app_mode == "LOL Dataset Explorer":
st.header("📂 LOL Dataset Browser")
st.write("Browse and compare ground truth vs low-light enhancement from the LOL dataset.")
samples = get_lol_dataset_samples()
if not samples:
st.info("Place the LOL dataset in folder: dataset/LOLdataset/low to use this feature.")
# Mock / Placeholder info
st.write("Dataset Structure Example:")
st.code("""
dataset/
└── LOLdataset/
├── low/ (485 images)
└── high/ (485 images)
""")
else:
selected_sample_name = st.selectbox("Select Sample", [s['name'] for s in samples])
sample = next(s for s in samples if s['name'] == selected_sample_name)
low, high = load_lol_pair(sample)
col1, col2, col3 = st.columns(3)
with col1:
st.subheader("Low Light (Input)")
st.image(low, use_container_width=True)
with col2:
st.subheader("Ground Truth")
st.image(high, use_container_width=True)
with col3:
st.subheader("PLL-SIE Enhanced")
res = enhancement_pipeline(low, {"gamma": gamma_val, "clahe_limit": clahe_clip, "denoise_h": denoise_h})
st.image(res, use_container_width=True)
elif app_mode == "Webcam Live":
st.header("🎥 Live Signal Capture")
st.markdown("Use your camera to capture and optimize dark environment frames.")
img_file_buffer = st.camera_input("Snapshot for Smart Optimization")
if img_file_buffer:
img = Image.open(img_file_buffer).convert("RGB")
img_np = np.array(img)
with st.spinner("Optimizing stream..."):
metrics = run_image_enhancement(img_np)
st.image(metrics['result'], caption="Optimized View Result")
elif app_mode == "Project Report":
# Check if README.md exists
if os.path.exists("README.md"):
with open("README.md", "r") as f:
st.markdown(f.read())
else:
st.error("Report (README.md) not found.")
if __name__ == "__main__":
main()