Phramer_AI / app.py
Malaji71's picture
Update app.py
ffcc74e verified
"""
Phramer AI - Main Gradio Interface
By Pariente AI, for MIA TV Series
Multimodal tool that reads images and turns them into refined, photo-realistic prompts.
Ready for Midjourney, Flux or any generative engine.
"""
import gradio as gr
import logging
import warnings
import os
from typing import Tuple
from config import APP_CONFIG, ENVIRONMENT
from processor import process_image_simple, phramer_optimizer
from utils import setup_logging, clean_memory
# Configure environment
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# Setup logging
setup_logging(ENVIRONMENT["log_level"])
logger = logging.getLogger(__name__)
def process_image_interface(image) -> Tuple[str, str, str]:
"""
Main interface function for image processing
Args:
image: Input image from Gradio interface
Returns:
Tuple of (prompt, analysis_report, score_html)
"""
try:
if image is None:
return (
"Please upload an image to analyze",
"No image provided for analysis.",
'<div style="text-align: center; padding: 1rem;"><div style="font-size: 2rem; color: #ccc;">--</div><div style="font-size: 0.875rem; color: #999;">Quality Score</div></div>'
)
logger.info("Processing image through Phramer AI interface")
prompt, report, score_html = process_image_simple(image)
return prompt, report, score_html
except Exception as e:
logger.error(f"Interface processing error: {e}", exc_info=True)
error_msg = f"Processing failed: {str(e)}"
return (
"❌ Processing failed",
f"**Error:** {error_msg}\n\nPlease try again with a different image.",
'<div style="text-align: center; padding: 1rem; color: red;"><div style="font-size: 2rem;">0</div><div style="font-size: 0.875rem;">Error</div></div>'
)
def clear_interface() -> Tuple[str, str, str]:
"""Clear all interface outputs and free memory"""
clean_memory()
logger.info("Interface cleared")
return (
"",
"",
'<div style="text-align: center; padding: 1rem;"><div style="font-size: 2rem; color: #ccc;">--</div><div style="font-size: 0.875rem; color: #999;">Quality Score</div></div>'
)
def get_stats_info() -> str:
"""Get current processing statistics"""
try:
stats = phramer_optimizer.get_enhanced_stats()
stats_text = f"""**Processing Statistics:**
• **Total Images:** {stats['total_processed']}
• **Successful:** {stats['successful_analyses']}
• **Failed:** {stats['failed_analyses']}
• **Success Rate:** {stats['success_rate']:.1%}
• **Average Time:** {stats['average_processing_time']:.1f}s
• **Device:** {stats['device_info']['device'].upper()}
"""
return stats_text
except Exception as e:
logger.error(f"Stats retrieval error: {e}")
return "Statistics unavailable"
def create_interface():
"""Create the main Gradio interface"""
# Updated CSS with Phramer AI branding
css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
.gradio-container {
max-width: 1600px !important;
margin: 0 auto !important;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%) !important;
}
/* Text visibility fixes */
.markdown-text, .markdown-text *,
.prose, .prose *,
.gr-markdown, .gr-markdown *,
div[class*="markdown"], div[class*="markdown"] * {
color: #1f2937 !important;
}
.markdown-text h1, .markdown-text h2, .markdown-text h3,
.prose h1, .prose h2, .prose h3,
.gr-markdown h1, .gr-markdown h2, .gr-markdown h3 {
color: #111827 !important;
font-weight: 700 !important;
}
.markdown-text p, .markdown-text li, .markdown-text ul, .markdown-text ol,
.prose p, .prose li, .prose ul, .prose ol,
.gr-markdown p, .gr-markdown li, .gr-markdown ul, .gr-markdown ol {
color: #374151 !important;
}
.markdown-text strong, .prose strong, .gr-markdown strong {
color: #111827 !important;
font-weight: 700 !important;
}
/* Header styling */
.main-header {
text-align: center;
padding: 3rem 0 4rem 0;
background: linear-gradient(135deg, #0c0a09 0%, #1c1917 30%, #292524 60%, #44403c 100%);
color: white;
margin: -2rem -2rem 3rem -2rem;
border-radius: 0 0 32px 32px;
box-shadow: 0 20px 50px -10px rgba(0, 0, 0, 0.25);
position: relative;
overflow: hidden;
}
.main-header::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(45deg, rgba(59, 130, 246, 0.1) 0%, rgba(147, 51, 234, 0.1) 50%, rgba(236, 72, 153, 0.1) 100%);
z-index: 1;
}
.main-title {
font-size: 4rem !important;
font-weight: 900 !important;
margin: 0 0 1rem 0 !important;
letter-spacing: -0.05em !important;
background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 25%, #8b5cf6 50%, #a855f7 75%, #ec4899 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
position: relative;
z-index: 2;
}
.subtitle {
font-size: 1.5rem !important;
font-weight: 500 !important;
opacity: 0.95 !important;
margin: 0 0 0.5rem 0 !important;
position: relative;
z-index: 2;
color: #ffffff !important;
}
.tagline {
font-size: 1.1rem !important;
font-weight: 400 !important;
opacity: 0.85 !important;
margin: 0 !important;
position: relative;
z-index: 2;
color: #e5e7eb !important;
font-style: italic;
}
.prompt-output {
font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace !important;
font-size: 15px !important;
line-height: 1.8 !important;
background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%) !important;
border: 2px solid #e2e8f0 !important;
border-radius: 20px !important;
padding: 2.5rem !important;
box-shadow: 0 20px 50px -10px rgba(0, 0, 0, 0.1) !important;
transition: all 0.3s ease !important;
color: #1f2937 !important;
}
.prompt-output:hover {
box-shadow: 0 25px 60px -5px rgba(0, 0, 0, 0.15) !important;
transform: translateY(-2px) !important;
}
"""
with gr.Blocks(
theme=gr.themes.Soft(),
title="Phramer AI",
css=css
) as interface:
gr.HTML("""
<div class="main-header">
<div class="main-title">Phramer AI</div>
<div class="subtitle">By Pariente AI, for MIA TV Series</div>
<div class="tagline">Multimodal tool that reads images and turns them into refined, photo-realistic prompts</div>
</div>
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## Image Analysis")
image_input = gr.Image(
label="Upload image for analysis",
type="pil",
height=500
)
analyze_btn = gr.Button(
"🔍 Generate Prompt",
variant="primary",
size="lg"
)
gr.Markdown("""
### How Phramer AI Works:
**1. Deep Analysis:** Custom Bagel architecture analyzes your image for semantic-visual understanding.
**2. Knowledge Enhancement:** Applies curated photographic knowledge base with camera settings and composition principles.
**3. Prompt Generation:** Creates structured prompts with technical details, mood, and style specifications.
**4. Multi-Engine Ready:** Optimized for Flux, Midjourney, and other diffusion platforms.
**Perfect for:** Cinematic storyboards, photorealistic scenes, visual concept exploration.
**Supported formats:** JPG, PNG, WebP up to 1024px
""")
# Statistics
with gr.Accordion("📊 Processing Statistics", open=False):
stats_output = gr.Markdown(value="No processing completed yet.")
refresh_stats_btn = gr.Button("Refresh Stats", size="sm")
with gr.Column(scale=1):
gr.Markdown("## Generated Prompt")
score_output = gr.HTML(
value='<div style="text-align: center; padding: 1rem;"><div style="font-size: 2rem; color: #ccc;">--</div><div style="font-size: 0.875rem; color: #999;">Quality Score</div></div>'
)
prompt_output = gr.Textbox(
label="🎯 Photo-Realistic Prompt",
placeholder="Upload an image to generate a refined prompt ready for any generative engine...",
lines=12,
max_lines=20,
show_copy_button=True
)
info_output = gr.Markdown(value="")
clear_btn = gr.Button("🗑️ Clear Analysis", size="sm")
# Event handlers
analyze_btn.click(
fn=process_image_interface,
inputs=[image_input],
outputs=[prompt_output, info_output, score_output]
)
clear_btn.click(
fn=clear_interface,
outputs=[prompt_output, info_output, score_output]
)
refresh_stats_btn.click(
fn=get_stats_info,
outputs=stats_output
)
gr.Markdown("""
---
### About Phramer AI
**Phramer AI** is an advanced multimodal system developed by **Pariente AI** for the **MIA TV Series** creative pipeline.
This tool bridges the gap between image understanding and generative prompting, analyzing uploaded images through
a custom Bagel architecture and enhancing them with professional photographic knowledge to create detailed,
structured prompts ready for Flux, Midjourney, or any diffusion-based platform.
Whether creating cinematic storyboards, photorealistic scenes, or exploring visual concepts, Phramer AI delivers
refined prompts with camera settings, composition hints, mood specifications, and style guidance.
**Pariente AI** • Advanced Multimodal AI Research & Development • **MIA TV Series**
""")
return interface
def main():
"""Main application entry point"""
logger.info("Starting Phramer AI by Pariente AI")
# Create and launch interface
demo = create_interface()
# Launch with proper configuration
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
show_error=True
)
if __name__ == "__main__":
main()