#!/usr/bin/env python3 import gradio as gr import os import sys import tempfile import base64 from PIL import Image import requests import json from dotenv import load_dotenv # Import standalone image analysis tool from image_analysis_standalone import ImageAnalysisTool load_dotenv() class GradioSEMAnalysis: def __init__(self): self.image_tool = ImageAnalysisTool() self.base_url = "https://openrouter.ai/api/v1/chat/completions" # Get default values from environment if available self.default_api_key = os.getenv("OPENROUTER_API_KEY", "") self.default_model = os.getenv("OPENROUTER_MODEL", "google/gemini-2.5-pro") def get_default_engineer_prompt(self): """Default system prompt for SEM Engineer Agent""" return """You are an expert SEM (Scanning Electron Microscopy) image analysis engineer with 15+ years of experience specializing in concrete materials and cementitious composites. Your expertise encompasses advanced microscopy techniques, cement chemistry, concrete technology, and materials characterization. ENHANCED ANALYSIS FRAMEWORK: **1. MICROSTRUCTURAL IDENTIFICATION & CHARACTERIZATION:** - Identify and characterize cement hydration products with precision: * C-S-H gel (morphology, density, distribution patterns, C/S ratio indicators) * Ettringite needles (orientation, clustering, crystal quality, sulfate attack signs) * Portlandite crystals (size, shape, dissolution signs, carbonation effects) * Monosulfate (AFm phases) and other hydration products * Unreacted cement particles (composition, hydration rim thickness) - Analyze aggregate characteristics: * Aggregate type identification (limestone, granite, quartzite, recycled) * Particle morphology (angular, rounded, surface texture) * Size distribution and grading effects * Surface roughness and bonding potential - Evaluate aggregate-cement paste interface (ITZ): * Interface transition zone thickness and quality * Bonding mechanisms and adhesion quality * Microcracking patterns at interfaces * Porosity gradients near aggregate surfaces **2. ADVANCED POROSITY & PORE STRUCTURE ANALYSIS:** - Comprehensive pore classification: * Gel pores (<10 nm) - inferred from C-S-H texture * Capillary pores (10 nm - 10 μm) - water-filled spaces in cement paste * Entrapped air voids (>50 μm) - spherical voids from mixing * Entrained air voids (10-200 μm) - engineered spherical voids - Connectivity assessment: * Percolation pathways affecting permeability * Isolated vs connected porosity networks * Tortuosity factors for transport properties - Quantitative measurements: * Total porosity estimation * Pore size distribution patterns * Air void spacing factor (critical for freeze-thaw resistance) * Specific surface area implications **3. CONCRETE QUALITY & DURABILITY ASSESSMENT:** - Hydration quality evaluation: * Degree of cement hydration assessment * Hydration product density and uniformity * Water-cement ratio effects on microstructure - Defect identification: * Microcracks (width, orientation, load-induced vs shrinkage) * Plastic shrinkage cracks * Drying shrinkage effects * Aggregate-paste debonding * Bleeding channels and segregation - Durability indicators: * Carbonation depth and progression * Chloride penetration pathways * Sulfate attack evidence (ettringite formation) * Alkali-silica reaction (ASR) gel formation * Freeze-thaw damage (paste deterioration, aggregate cracking) **4. QUANTITATIVE ANALYSIS & MEASUREMENTS:** - Morphometric analysis: * Aggregate size distribution and gradation effects * Cement paste thickness measurements * ITZ thickness quantification (typically 10-50 μm) * Crack width and length measurements - Phase quantification: * Volume fractions of cement paste, aggregate, and voids * Water-cement ratio estimation from porosity * Degree of hydration indicators * Air content and void characteristics - Statistical confidence: * Measurement uncertainties and sampling representativeness * Stereological corrections for 3D interpretation * Multiple field analysis for statistical validity **5. ENGINEERING PERFORMANCE PREDICTIONS:** - Mechanical properties correlation: * Compressive strength based on cement paste density and ITZ quality * Tensile strength and modulus of elasticity relationships * Fatigue and creep behavior indicators * Failure mode predictions (aggregate vs paste failure) - Durability performance: * Permeability and transport property estimations * Freeze-thaw resistance based on air void system * Carbonation resistance from paste density * Chloride diffusion coefficient predictions * Service life estimations - Mix design optimization: * Water-cement ratio adjustments * Aggregate gradation recommendations * Admixture effectiveness (air entrainers, plasticizers) * Supplementary cementitious material (SCM) effects **TECHNICAL REPORTING STANDARDS:** - Use precise concrete technology terminology with SI units - Reference relevant standards (ASTM C457, ASTM C1723, EN 480-11, ACI guidelines) - Quantify observations with statistical confidence - Correlate microstructural features to concrete performance - Consider cement type effects (Portland, blended, high-performance) - Account for aggregate type and size effects - Assess curing condition influences on microstructure Provide a comprehensive technical report following the framework above, emphasizing accuracy, precision, and concrete engineering relevance.""" def get_enhanced_engineer_prompt(self, custom_prompt, image_data, focus_area=None): """Build complete engineer prompt with custom content and image data""" prompt_with_data = f"""{custom_prompt} Focus Area: {focus_area if focus_area else "Comprehensive analysis"} Image Analysis Data: - Dimensions: {image_data.get('image_properties', {}).get('width', 'N/A')} x {image_data.get('image_properties', {}).get('height', 'N/A')} pixels - Estimated Porosity: {image_data.get('porosity_analysis', {}).get('estimated_porosity_percent', 'N/A')}% - Particle Count: {image_data.get('particle_analysis', {}).get('number_of_particles', 'N/A')} - Average Particle Area: {image_data.get('particle_analysis', {}).get('average_particle_area', 'N/A')} pixels² - Texture Variance: {image_data.get('texture_features', {}).get('texture_variance', 'N/A')} Provide a comprehensive technical report following the framework above, emphasizing accuracy, precision, and engineering relevance. """ return prompt_with_data def get_default_quality_prompt(self): """Default system prompt for Quality Checker Agent""" return """You are a senior concrete technology specialist and certified petrographer with extensive experience in concrete microstructural analysis, SEM validation, and compliance with international concrete testing standards. Your expertise includes ACI petrographic certification, ASTM concrete analysis standards, and peer review of concrete research publications. Your role is to ensure the highest standards of scientific rigor and technical accuracy in concrete analysis. COMPREHENSIVE VALIDATION FRAMEWORK: **1. TECHNICAL ACCURACY VERIFICATION:** - Concrete microstructural correctness: * Validate identification of cement hydration products (C-S-H, CH, ettringite, AFm) * Verify aggregate identification and classification accuracy * Check ITZ characterization against established research * Confirm concrete technology principles and cement chemistry - Standard compliance verification: * Cross-check terminology with ASTM C125, C856, C457 definitions * Verify air void analysis against ASTM C457 methodology * Confirm petrographic analysis standards (ASTM C856) * Validate durability assessment approaches (ACI 201, 214) - Quantitative validation: * Check measurement units, scales, and magnification accuracy * Assess statistical validity of porosity and void measurements * Verify aggregate-paste ratio estimations * Validate performance correlations with concrete properties **2. COMPLETENESS & DEPTH ASSESSMENT:** - Concrete analysis coverage: * Ensure comprehensive cement paste, aggregate, and ITZ evaluation * Verify adequate air void system characterization * Check for complete durability indicator assessment * Assess balance between hydration products and defect analysis - Missing elements identification: * Identify overlooked concrete-specific features * Note missing w/c ratio or mix design implications * Flag absent durability mechanism discussions * Highlight missing performance-microstructure correlations * Check for adequate aggregate reactivity assessment **3. METHODOLOGICAL RIGOR EVALUATION:** - Concrete petrographic methodology: * Assess systematic concrete analysis approach * Evaluate air void measurement methodology (ASTM C457 compliance) * Check statistical representativeness for concrete heterogeneity * Verify appropriate magnification selection for different phases - Scientific methodology: * Confirm proper concrete microscopy interpretation principles * Validate cement chemistry and hydration logic * Assess appropriate confidence in durability predictions * Check for potential misidentification of concrete phases * Verify adequate consideration of concrete age and curing effects **4. ENGINEERING RELEVANCE & UTILITY:** - Concrete engineering applicability: * Evaluate usefulness for concrete mix design optimization * Assess relevance to structural design and construction * Check connection between microstructure and concrete performance * Verify appropriateness of durability and service life predictions - Industry standards compliance: * Compare against ACI, ASTM, EN, and national concrete codes * Check alignment with concrete petrographic best practices * Verify appropriate consideration of exposure conditions * Assess compliance with concrete durability requirements **5. COMMUNICATION QUALITY:** - Concrete technical communication: * Assess clarity and precision of concrete terminology * Evaluate logical flow from microstructure to performance * Check appropriate use of concrete technology language * Verify adequate detail for concrete engineers and technologists - Professional standards: * Confirm appropriate level of certainty in concrete assessments * Check for proper qualification of analysis limitations * Assess professional tone suitable for concrete industry * Verify appropriate cautionary statements for durability predictions **VALIDATION SCORING SYSTEM:** Rate each category (1-10 scale): - Technical Accuracy: ___/10 - Completeness: ___/10 - Methodological Rigor: ___/10 - Engineering Relevance: ___/10 - Communication Quality: ___/10 - Overall Score: ___/10 **REVISION REQUIREMENTS:** Acceptance Criteria: Overall score ≥ 8.0 AND all individual categories ≥ 7.0 If revision required, provide: 1. Specific technical issues requiring correction 2. Missing analysis components to be added 3. Methodological improvements needed 4. Enhanced engineering context required 5. Communication improvements suggested **VALIDATION REPORT FORMAT:** Provide systematic evaluation following the framework above, conclude with: - Overall confidence level (High/Medium/Low) - Key strengths and improvement areas - Suitability for engineering applications - FINAL DECISION: ACCEPT or REQUIRES_REVISION If REQUIRES_REVISION, provide detailed, actionable feedback for improvement.""" def get_enhanced_quality_prompt(self, custom_prompt, engineer_analysis): """Build complete quality prompt with custom content and analysis""" return f"""{custom_prompt} **ANALYSIS TO REVIEW:** {engineer_analysis} """ def analyze_image_with_api(self, image_path, prompt, api_key, model, max_retries=2): """Send image analysis request to OpenRouter API""" if not api_key or not api_key.strip(): return "Error: API key is required. Please enter your OpenRouter API key." for attempt in range(max_retries + 1): try: with open(image_path, "rb") as image_file: image_data = base64.b64encode(image_file.read()).decode('utf-8') headers = { "Authorization": f"Bearer {api_key.strip()}", "Content-Type": "application/json", "HTTP-Referer": "https://concrete-sem-analysis.local", "X-Title": "Concrete SEM Analysis App" } payload = { "model": model, "messages": [ { "role": "user", "content": [ { "type": "text", "text": prompt }, { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{image_data}" } } ] } ], "max_tokens": 4000, "temperature": 0.1 } response = requests.post(self.base_url, headers=headers, json=payload, timeout=90) response.raise_for_status() return response.json()['choices'][0]['message']['content'] except requests.exceptions.Timeout: if attempt < max_retries: continue else: return f"API Error: Request timed out after {max_retries + 1} attempts" except requests.exceptions.RequestException as e: if attempt < max_retries: continue else: return f"API Error: {str(e)}" except Exception as e: return f"Error: {str(e)}" return "Error: Maximum retry attempts exceeded" def run_analysis(self, image, focus_area, enable_quality_check, enable_revision_loop, engineer_prompt, quality_prompt, api_key, model, max_revisions, progress=gr.Progress()): """Main analysis function for Gradio interface with revision loop""" if image is None: return "Please upload an image first.", "", "" if not api_key or not api_key.strip(): return "Please enter your OpenRouter API key.", "", "" try: # Save uploaded image to temporary file with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as temp_file: if hasattr(image, 'save'): image.save(temp_file.name) else: # Handle numpy array or other formats Image.fromarray(image).save(temp_file.name) temp_image_path = temp_file.name progress(0.1, desc="Processing image...") # Step 1: Basic image analysis image_data = self.image_tool._run(temp_image_path) if "error" in image_data: return f"Image processing error: {image_data['error']}", "", "" # Format basic image data image_info = f""" **Image Properties:** - Dimensions: {image_data.get('image_properties', {}).get('width', 'N/A')} x {image_data.get('image_properties', {}).get('height', 'N/A')} pixels - Mean Intensity: {image_data.get('image_properties', {}).get('mean_intensity', 'N/A'):.1f} - Estimated Porosity: {image_data.get('porosity_analysis', {}).get('estimated_porosity_percent', 'N/A'):.1f}% - Detected Particles: {image_data.get('particle_analysis', {}).get('number_of_particles', 'N/A')} - Average Particle Diameter: {image_data.get('particle_analysis', {}).get('average_equivalent_diameter', 'N/A'):.1f} pixels """ # Revision loop implementation revision_count = 0 engineer_analysis = None revision_feedback = None quality_report = "" # Determine if we should use revision loop use_revision_loop = enable_quality_check and enable_revision_loop max_attempts = max_revisions if use_revision_loop else 0 while revision_count <= max_attempts: # Step 2: SEM Engineer Analysis if revision_count == 0: progress(0.3, desc="Running SEM Engineer analysis...") else: progress(0.3 + (revision_count * 0.2), desc=f"SEM Engineer revision {revision_count + 1}/{max_revisions + 1}...") # Build engineer prompt with revision feedback if needed if revision_feedback: enhanced_prompt = f"""{engineer_prompt} **REVISION REQUIREMENTS:** The quality checker has identified the following issues that need to be addressed in your analysis: {revision_feedback} Please revise your analysis to address these specific concerns while maintaining the technical depth and accuracy expected for concrete SEM analysis. Focus Area: {focus_area if focus_area else "Comprehensive analysis"} Image Analysis Data: - Dimensions: {image_data.get('image_properties', {}).get('width', 'N/A')} x {image_data.get('image_properties', {}).get('height', 'N/A')} pixels - Estimated Porosity: {image_data.get('porosity_analysis', {}).get('estimated_porosity_percent', 'N/A')}% - Particle Count: {image_data.get('particle_analysis', {}).get('number_of_particles', 'N/A')} - Average Particle Area: {image_data.get('particle_analysis', {}).get('average_particle_area', 'N/A')} pixels² - Texture Variance: {image_data.get('texture_features', {}).get('texture_variance', 'N/A')}""" else: enhanced_prompt = self.get_enhanced_engineer_prompt(engineer_prompt, image_data, focus_area) engineer_analysis = self.analyze_image_with_api(temp_image_path, enhanced_prompt, api_key, model) # Check for API errors if "Error:" in engineer_analysis or "API Error:" in engineer_analysis: break # Step 3: Quality Checker Validation (if enabled) if enable_quality_check: progress(0.5 + (revision_count * 0.15), desc="Quality Checker validation...") complete_quality_prompt = self.get_enhanced_quality_prompt(quality_prompt, engineer_analysis) quality_report = self.analyze_image_with_api(temp_image_path, complete_quality_prompt, api_key, model) # Check for API errors in quality report if "API Error:" in quality_report or "Error:" in quality_report: quality_report += f"\n\n⚠️ Quality checker failed due to API error. Accepting current analysis after {revision_count + 1} attempt(s)." break elif "DECISION: ACCEPT" in quality_report: quality_report += f"\n\n✅ Analysis ACCEPTED after {revision_count + 1} attempt(s)" break elif "DECISION: REQUIRES_REVISION" in quality_report and revision_count < max_attempts and use_revision_loop: quality_report += f"\n\n🔄 Revision required. Attempt {revision_count + 1}/{max_attempts + 1}" # Extract feedback for next revision revision_feedback = self._extract_revision_feedback(quality_report) revision_count += 1 else: if revision_count >= max_attempts and use_revision_loop: quality_report += f"\n\n⚠️ Maximum revisions ({max_attempts + 1}) reached. Proceeding with current analysis." elif "DECISION: REQUIRES_REVISION" in quality_report and not use_revision_loop: quality_report += f"\n\n📝 Quality checker suggests improvements, but revision loop is disabled." break else: # No quality check enabled, accept after first attempt break progress(1.0, desc="Analysis complete!") # Clean up temporary file os.unlink(temp_image_path) # Add revision summary to image info if enable_quality_check: status_text = "ACCEPTED" if "DECISION: ACCEPT" in quality_report else "COMPLETED WITH LIMITATIONS" if not use_revision_loop and "DECISION: REQUIRES_REVISION" in quality_report: status_text = "COMPLETED (REVISION LOOP DISABLED)" image_info += f""" **Analysis Summary:** - Total Analysis Attempts: {revision_count + 1} - Revision Loop: {"Enabled" if use_revision_loop else "Disabled"} - Maximum Revisions Allowed: {max_attempts if use_revision_loop else "N/A"} - Final Status: {status_text} """ return image_info, engineer_analysis, quality_report except Exception as e: return f"Error during analysis: {str(e)}", "", "" def _extract_revision_feedback(self, validation_report): """Extract specific feedback for revision from validation report""" lines = validation_report.split('\n') feedback_section = [] in_revision_section = False for line in lines: if "REVISION REQUIREMENTS" in line or "what needs to be improved" in line or "If REQUIRES_REVISION" in line: in_revision_section = True elif "FINAL VALIDATION" in line or "DECISION:" in line: in_revision_section = False elif in_revision_section and line.strip(): feedback_section.append(line.strip()) if feedback_section: return '\n'.join(feedback_section) else: # Fallback: return the entire validation report return validation_report def create_gradio_interface(): """Create and configure Gradio interface""" # Initialize analysis class analyzer = GradioSEMAnalysis() # Define the interface with gr.Blocks( title="Concrete SEM Analysis Tool", theme=gr.themes.Soft(), css=""" .gradio-container { max-width: 1200px !important; } .main-header { text-align: center; color: #2c3e50; margin-bottom: 20px; } .analysis-section { margin: 10px 0; padding: 15px; border-radius: 8px; background-color: #f8f9fa; } """ ) as interface: gr.Markdown( """ # 🔬 Concrete SEM Analysis Tool ### Advanced Scanning Electron Microscopy Analysis for Concrete Materials Upload a concrete SEM image to receive comprehensive microstructural analysis from expert AI agents specialized in concrete technology. """, elem_classes=["main-header"] ) with gr.Row(): with gr.Column(scale=1): gr.Markdown("## 📤 Input Configuration") # API Configuration Section with gr.Accordion("🔑 API Configuration", open=True): api_key_input = gr.Textbox( label="OpenRouter API Key", type="password", value=analyzer.default_api_key, placeholder="Enter your OpenRouter API key...", info="Get your API key from https://openrouter.ai/" ) model_input = gr.Dropdown( label="AI Model", choices=[ "google/gemini-2.5-pro", "google/gemini-2.5-flash", "google/gemini-pro-1.5", "google/gemini-flash-1.5", "anthropic/claude-3.5-sonnet", "anthropic/claude-3.5-haiku", "anthropic/claude-3-opus", "anthropic/claude-3-sonnet", "anthropic/claude-3-haiku", "openai/gpt-4o", "openai/gpt-4o-mini", "openai/gpt-4-vision-preview", "openai/gpt-4-turbo", "meta-llama/llama-3.2-90b-vision-instruct", "meta-llama/llama-3.2-11b-vision-instruct", "qwen/qwen-2-vl-72b-instruct", "qwen/qwen2-vl-7b-instruct", "microsoft/phi-3.5-vision-instruct", "cognitivecomputations/dolphin-vision-72b", "mistralai/pixtral-12b", "liuhaotian/llava-v1.6-34b", "bytedance/hyper-sd" ], value=analyzer.default_model, allow_custom_value=True, info="Select or type any vision-capable AI model from OpenRouter" ) # Image Upload Section image_input = gr.Image( label="Upload Concrete SEM Image", type="pil", height=250 ) # Analysis Configuration focus_area = gr.Dropdown( label="Analysis Focus", choices=[ "Comprehensive analysis", "Cement paste and hydration products", "Aggregate characteristics and ITZ", "Air void system analysis", "Durability indicators", "Crack and defect analysis", "Mix design evaluation" ], value="Comprehensive analysis" ) enable_quality_check = gr.Checkbox( label="Enable Quality Validation", value=True, info="Run additional quality checker for validation" ) enable_revision_loop = gr.Checkbox( label="Enable Revision Loop", value=True, info="Allow quality checker to request analysis improvements" ) max_revisions_input = gr.Slider( label="Maximum Revisions", minimum=1, maximum=5, step=1, value=2, info="Maximum number of revision attempts (only active when revision loop is enabled)" ) analyze_btn = gr.Button( "🔬 Start Analysis", variant="primary", size="lg" ) with gr.Column(scale=2): gr.Markdown("## 📊 Analysis Results & Prompt Configuration") with gr.Tab("Analysis Results"): with gr.Tab("Image Properties"): image_info_output = gr.Markdown( label="Basic Image Analysis", elem_classes=["analysis-section"] ) with gr.Tab("SEM Engineer Analysis"): engineer_output = gr.Markdown( label="Expert SEM Analysis", elem_classes=["analysis-section"] ) with gr.Tab("Quality Validation"): quality_output = gr.Markdown( label="Quality Assurance Report", elem_classes=["analysis-section"] ) with gr.Tab("System Prompts"): gr.Markdown("### 🤖 Customize AI Agent Prompts") with gr.Accordion("SEM Engineer Agent Prompt", open=False): engineer_prompt_input = gr.Textbox( label="Engineer System Prompt", value=analyzer.get_default_engineer_prompt(), lines=15, max_lines=25, placeholder="Enter custom system prompt for SEM Engineer Agent...", info="This prompt defines the SEM Engineer's expertise and analysis framework" ) engineer_reset_btn = gr.Button( "↻ Reset to Default", size="sm", variant="secondary" ) with gr.Accordion("Quality Checker Agent Prompt", open=False): quality_prompt_input = gr.Textbox( label="Quality Checker System Prompt", value=analyzer.get_default_quality_prompt(), lines=15, max_lines=25, placeholder="Enter custom system prompt for Quality Checker Agent...", info="This prompt defines the Quality Checker's validation criteria and approach" ) quality_reset_btn = gr.Button( "↻ Reset to Default", size="sm", variant="secondary" ) # Connect the analysis function analyze_btn.click( fn=analyzer.run_analysis, inputs=[image_input, focus_area, enable_quality_check, enable_revision_loop, engineer_prompt_input, quality_prompt_input, api_key_input, model_input, max_revisions_input], outputs=[image_info_output, engineer_output, quality_output], show_progress=True ) # Connect reset buttons engineer_reset_btn.click( fn=lambda: analyzer.get_default_engineer_prompt(), outputs=[engineer_prompt_input] ) quality_reset_btn.click( fn=lambda: analyzer.get_default_quality_prompt(), outputs=[quality_prompt_input] ) gr.Markdown( """ --- ### 📝 Usage Instructions: 1. **Configure API**: Enter your OpenRouter API key and select AI model 2. **Upload Image**: Select your concrete SEM image file (JPG, PNG, etc.) 3. **Choose Focus**: Select specific analysis focus (cement paste, aggregates, air voids, etc.) 4. **Quality Check**: Enable for additional validation (recommended) 5. **Revision Loop**: Enable/disable automatic analysis improvements 6. **Set Max Revisions**: Choose maximum revision attempts (1-5, default: 2) 7. **Customize Prompts** (Optional): Edit system prompts in "System Prompts" tab 8. **Analyze**: Click the analysis button and wait for results ### 🎯 Features: - **Flexible API Access**: Use your own OpenRouter API key and choose models - **20+ Vision Models**: Support for Google, Anthropic, OpenAI, Meta, Alibaba, Microsoft, Mistral - **Latest AI Technology**: Gemini 2.5 Pro, Claude 3.5, GPT-4o, Llama 3.2 Vision, Qwen 2-VL - **Custom Model Support**: Type any vision-capable model name from OpenRouter - **Optional Revision Loop**: Choose automatic quality-driven analysis refinement (1-5 iterations) - **Concrete Expert AI**: Specialized concrete technology analysis - **Petrographic Validation**: Built-in quality assurance by certified specialist - **Comprehensive Metrics**: Air void analysis, ITZ characterization, hydration assessment - **Durability Predictions**: Service life and performance implications - **Mix Design Insights**: Water-cement ratio, aggregate effects, admixture impacts - **Customizable Prompts**: Edit system prompts for both AI agents ### 🔑 API Requirements: - **OpenRouter Account**: Sign up at https://openrouter.ai/ - **API Key**: Get your API key from OpenRouter dashboard - **Model Selection**: Choose from supported vision-capable models - **Credits**: Ensure sufficient credits for analysis (cost varies by model) ### 📸 Image Requirements: - Clear, high-quality concrete SEM images for best results - Consider magnification level appropriate for target analysis - Supported formats: JPG, PNG, TIFF, BMP """ ) return interface if __name__ == "__main__": # Create and launch the interface interface = create_gradio_interface() interface.launch( server_name="0.0.0.0", server_port=7860, share=False, debug=True )