File size: 34,315 Bytes
a22e992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
#!/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
    )