import gradio as gr
from backend.lcm_text_to_image import LCMTextToImage
from backend.models.lcmdiffusion_setting import LCMLora, LCMDiffusionSetting
from constants import DEVICE, LCM_DEFAULT_MODEL_OPENVINO
from time import perf_counter
import numpy as np
from cv2 import imencode
import base64
from backend.device import get_device_name
from constants import APP_VERSION
from backend.device import is_openvino_device
from PIL import Image
from backend.models.lcmdiffusion_setting import DiffusionTask
from backend.safety_check import is_safe_image
from pprint import pprint
from transformers import pipeline
import os
lcm_text_to_image = LCMTextToImage()
lcm_lora = LCMLora(
base_model_id="Lykon/dreamshaper-7",
lcm_lora_id="latent-consistency/lcm-lora-sdv1-5",
)
classifier = pipeline(
"image-classification",
model="Falconsai/nsfw_image_detection",
)
# https://github.com/gradio-app/gradio/issues/2635#issuecomment-1423531319
def encode_pil_to_base64_new(pil_image):
image_arr = np.asarray(pil_image)[:, :, ::-1]
_, byte_data = imencode(".png", image_arr)
base64_data = base64.b64encode(byte_data)
base64_string_opencv = base64_data.decode("utf-8")
return "data:image/png;base64," + base64_string_opencv
# monkey patching encode pil
gr.processing_utils.encode_pil_to_base64 = encode_pil_to_base64_new
def get_logo_html():
"""Get the AEGIS logo HTML with proper path handling"""
logo_path = "logo/aegis.jpeg"
# Check if logo exists
if os.path.exists(logo_path):
# For local development, use relative path
return f"""
"""
else:
# Fallback with emoji if logo not found
return """
π§¬
AEGIS Bio-Digital Lab 10
"""
def predict(
prompt,
steps,
seed,
use_seed,
):
print(f"prompt - {prompt}")
lcm_diffusion_setting = LCMDiffusionSetting()
lcm_diffusion_setting.lcm_model_id = "rupeshs/hyper-sd-sdxl-1-step"
lcm_diffusion_setting.diffusion_task = DiffusionTask.text_to_image.value
lcm_diffusion_setting.openvino_lcm_model_id = "rupeshs/sd-turbo-openvino"
lcm_diffusion_setting.use_lcm_lora = False
lcm_diffusion_setting.prompt = prompt
lcm_diffusion_setting.guidance_scale = 1.0
lcm_diffusion_setting.inference_steps = steps
lcm_diffusion_setting.seed = seed
lcm_diffusion_setting.use_seed = use_seed
lcm_diffusion_setting.use_safety_checker = True
lcm_diffusion_setting.use_tiny_auto_encoder = False
# lcm_diffusion_setting.image_width = 320 if is_openvino_device() else 512
# lcm_diffusion_setting.image_height = 320 if is_openvino_device() else 512
lcm_diffusion_setting.image_width = 512
lcm_diffusion_setting.image_height = 512
lcm_diffusion_setting.use_openvino = True
lcm_diffusion_setting.use_tiny_auto_encoder = True
pprint(lcm_diffusion_setting.model_dump())
lcm_text_to_image.init(lcm_diffusion_setting=lcm_diffusion_setting)
start = perf_counter()
images = lcm_text_to_image.generate(lcm_diffusion_setting)
latency = perf_counter() - start
print(f"Latency: {latency:.2f} seconds")
result = images[0]
if is_safe_image(
classifier,
result,
):
return result # .resize([512, 512], Image.LANCZOS)
else:
print("Unsafe image detected")
return Image.new("RGB", (512, 512), (0, 0, 0))
css = """
#container{
margin: 0 auto;
max-width: 55rem;
background: rgba(255, 255, 255, 0.95);
border-radius: 15px;
padding: 25px;
box-shadow: 0 8px 32px rgba(0,0,0,0.1);
backdrop-filter: blur(10px);
border: 2px solid rgba(30, 60, 114, 0.3);
}
#intro{
max-width: 100%;
text-align: center;
margin: 0 auto;
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
color: white;
padding: 25px;
border-radius: 12px;
margin-bottom: 20px;
box-shadow: 0 6px 20px rgba(30, 60, 114, 0.4);
border: 1px solid rgba(255,255,255,0.2);
}
#aegis_logo {
text-align: center;
margin-bottom: 20px;
padding: 10px;
}
#aegis_logo img {
max-width: 200px;
height: auto;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(30, 60, 114, 0.3);
transition: all 0.3s ease;
}
#aegis_logo img:hover {
transform: scale(1.05);
box-shadow: 0 6px 20px rgba(30, 60, 114, 0.5);
}
.mission-section {
background: linear-gradient(135deg, #2c1810 0%, #8b4513 50%, #d2691e 100%);
padding: 25px;
border-radius: 12px;
margin: 20px 0;
color: white;
box-shadow: 0 8px 25px rgba(139, 69, 19, 0.4);
}
.investment-section {
background: linear-gradient(135deg, #1a472a 0%, #2d5a3d 50%, #4a7c59 100%);
padding: 25px;
border-radius: 12px;
margin: 20px 0;
color: white;
box-shadow: 0 8px 25px rgba(26, 71, 42, 0.4);
}
.quadrant-section {
background: linear-gradient(135deg, #4a148c 0%, #7b1fa2 50%, #9c27b0 100%);
padding: 25px;
border-radius: 12px;
margin: 20px 0;
color: white;
box-shadow: 0 8px 25px rgba(74, 20, 140, 0.4);
}
.contact-section {
background: linear-gradient(135deg, #b71c1c 0%, #d32f2f 50%, #f44336 100%);
padding: 20px;
border-radius: 12px;
margin: 20px 0;
color: white;
text-align: center;
box-shadow: 0 8px 25px rgba(183, 28, 28, 0.4);
}
#generate_button {
color: white;
border-color: #1e3c72;
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
width: 200px;
height: 60px;
border-radius: 10px;
font-weight: bold;
font-size: 16px;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(30, 60, 114, 0.3);
}
#generate_button:hover {
transform: translateY(-3px);
box-shadow: 0 8px 25px rgba(30, 60, 114, 0.5);
background: linear-gradient(135deg, #2a5298 0%, #1e3c72 100%);
}
footer {
visibility: hidden
}
body {
background: linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%);
min-height: 100vh;
}
.gradio-container {
background: linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%);
min-height: 100vh;
}
.gr-textbox {
border: 2px solid #1e3c72;
border-radius: 8px;
background: rgba(255,255,255,0.95);
}
.gr-slider {
accent-color: #1e3c72;
}
.gr-accordion {
background: rgba(30, 60, 114, 0.1);
border: 1px solid rgba(30, 60, 114, 0.3);
border-radius: 8px;
}
"""
def _get_footer_message() -> str:
version = f" {APP_VERSION} "
footer_msg = version + (
' Β© 2025 | Gaston Software Solutions Tec | '
'Tel/WhatsApp: +256755274944 | '
'Email: gastonsoftwaresolution234@gmail.com | '
'AEGIS Bio-Digital Lab 10
'
)
warning_msg = """
𧬠AEGIS Bio-Digital Lab 10 - Advanced Bio-Digital Synthesis Platform
Powered by: Sovereign Quadrant AI β Synthesizing Reasoning, Genomics, Microscopy, and Volumetric Data
A Product of: Gaston Software Solutions Tec | Connect: Tel: +256755274944
For research and simulation purposes.
"""
# Green footer section
green_footer = f"""
"""
return warning_msg + green_footer
with gr.Blocks(css=css) as demo:
with gr.Column(elem_id="container"):
# AEGIS Logo at the top center
gr.HTML(get_logo_html())
use_openvino = "" if is_openvino_device() else ""
gr.Markdown(
f"""# 𧬠AEGIS Bio-Digital Lab 10 {use_openvino}
**Artificially Expanded Genetic Information System**
**Visualizing the Fabric of Life and Technology Through Time**
*Advanced generative intelligence platform transforming complex scientific and technological concepts into high-fidelity visualizations*
**Device:** {DEVICE.upper()} , {get_device_name()} | OpenVINO | **Powered by Sovereign Quadrant AI**
""",
elem_id="intro",
)
# Mission Statement: The Sovereign Timeline Project
gr.HTML("""
π― Mission Statement: The Sovereign Timeline Project
Our mission is to build a predictive immune system for humanity. The Artificially Expanded Genetic Information System (AEGIS) β Bio-Digital Lab 10 is not a tool for the present, but a shield for the future. We are developing the world's first temporal bio-digital modeling platform to visualize, understand, and preemptively counteract global biological threats before they emerge.
By simulating pathogen evolution, mapping the hidden pathways of future pandemics, and designing proactive countermeasures across projected timelines, we aim to transform global health security from a reactive struggle into a predictive science.
""")
# Investment Call to Action
gr.HTML("""
π’ Investment Call: Partner in the Sovereign Timeline
The next great leap in human survival will not be fought in clinics alone, but in the sovereign digital space where time itself becomes a variable.
π° Invest in the Predictive Frontier
Your capital will directly fuel the core engines of the Sovereign Quadrant:
- Expand the Timeline: Scale our high-fidelity models to simulate decades, not years, of viral and technological evolution.
- Fortify the Dataverse: Integrate next-generation genomic, climate, and epidemiological datasets to increase predictive accuracy.
- Democratize the Shield: Deploy public-facing simulation modules (like this Space) to accelerate global research and preparedness.
"This is more than an investment in technology. It is an investment in timeβbuying humanity the critical hours, days, and years needed to prevent the next crisis."
""")
# Sovereign Quadrant Visual
gr.HTML("""
π§ The Sovereign Quadrant Engine
π§ REASONING
Nemotron AI
π¬ MICROSCOPY
2D/3D Imaging
π VOLUME
Temporal Models
"Building the mirror that shows us our future, so we can change it."
""")
# Strategic Partnership Contact
gr.HTML("""
π€ Strategic Investment Discussions
Gaston Software Solutions Tec | Sovereign Timeline Division
Tel: +256755274944
Contact us to join the mission of building humanity's predictive immune system
""")
gr.HTML(
f"""
π¬ Bio-Digital Synthesis Modules
π¦ Pathogen Timeline
Models morphological evolution of viruses & bacteria across time
𧬠Synthetic Genomics
Renders novel genetic circuits and AEGIS base pair structures
π¬ Multi-Scale Imaging
From atomic protein folds to tissue-level pathology
βοΈ Tech-Bio Fusion
Bio-hybrid devices and computational biological systems
"""
)
with gr.Row():
with gr.Column(scale=2):
gr.HTML("""
𧬠Bio-Digital Synthesis Instructions
- Select Temporal Domain: Past (historical pandemics), Present (current lab models), Future (speculative synthetic biology)
- Define Subject: Input target organism, mechanism, or bio-tech fusion concept
- Set Parameters: Adjust complexity, style (schematic vs. photorealistic), resolution
- Synthesize: Generate unique bio-digital visualization
Example Prompts:
β’ "3D timeline showing influenza virus spike protein variation from 1918 to present"
β’ "Glowing schematic view of expanded DNA helix with synthetic nucleotides"
β’ "Cross-section from atomic detail of receptor to full cellular infection event"
β’ "Neural interface device with organic circuitry integrated with semiconductor layers"
""")
with gr.Row():
prompt = gr.Textbox(
placeholder="Example: 'Generate a photorealistic cross-sectional view of a hypothesized Martian extremophile bacterium, based on terrestrial archaea genetics, with radiation-resistant protein capsid. Style: scientific illustration with labeled components.'",
scale=5,
container=False,
lines=3,
label="𧬠Bio-Digital Synthesis Prompt"
)
generate_btn = gr.Button(
"π¬ Synthesize",
scale=1,
elem_id="generate_button",
)
image = gr.Image(type="filepath", label="𧬠Bio-Digital Visualization Output")
with gr.Accordion("π¬ Advanced Bio-Digital Parameters", open=False):
gr.HTML("""
Temporal Domains: Past (1800-1999) | Present (2000-2024) | Future (2025-2100)
Visualization Styles: Schematic, Photorealistic, Scientific Illustration, Cross-sectional
""")
steps = gr.Slider(
label="π¬ Synthesis Complexity",
value=1,
minimum=1,
maximum=3,
step=1,
info="Higher values = more detailed bio-digital rendering"
)
seed = gr.Slider(
randomize=True,
minimum=0,
maximum=999999999,
label="𧬠Genetic Seed",
step=1,
info="Reproducible bio-digital synthesis"
)
seed_checkbox = gr.Checkbox(
label="π Lock Genetic Seed",
value=False,
interactive=True,
)
gr.HTML(_get_footer_message())
inputs = [prompt, steps, seed, seed_checkbox]
generate_btn.click(fn=predict, inputs=inputs, outputs=image)
def start_demo_text_to_image(share=False):
demo.queue()
demo.launch(share=share)