đĄ ACCEPTIN
AI-Powered Telecom Site Quality Inspector
#!/usr/bin/env python3
"""
ACCEPTIN - Telecom Site Quality Classification App
AI-powered telecom site inspection using ConvNeXt transfer learning
"""
import streamlit as st
import torch
import torch.nn.functional as F
from PIL import Image
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import pandas as pd
import sys
import os
import time
from io import BytesIO
import base64
# Add utils to path
sys.path.append('utils')
from model_utils import load_model, TelecomClassifier
from data_utils import get_inference_transform, prepare_image_for_inference, check_data_directory
# Page Configuration
st.set_page_config(
page_title="đĄ ACCEPTIN - Telecom Site Inspector",
page_icon="đĄ",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for Beautiful UI
st.markdown("""
""", unsafe_allow_html=True)
@st.cache_resource
def load_telecom_model():
"""Load the trained telecom classification model"""
model_path = 'models/telecom_classifier.pth'
if not os.path.exists(model_path):
return None, "Model not found. Please train the model first."
try:
model, model_info = load_model(model_path, device='cpu')
return model, model_info
except Exception as e:
return None, f"Error loading model: {str(e)}"
def get_prediction(image, model, transform):
"""Get prediction from the model"""
try:
# Prepare image
input_tensor = prepare_image_for_inference(image, transform)
# Get prediction
with torch.no_grad():
model.eval()
outputs = model(input_tensor)
probabilities = F.softmax(outputs, dim=1)
confidence, predicted = torch.max(probabilities, 1)
# Convert to numpy
predicted_class = predicted.item()
confidence_score = confidence.item()
all_probs = probabilities.squeeze().cpu().numpy()
return predicted_class, confidence_score, all_probs
except Exception as e:
st.error(f"Error during prediction: {str(e)}")
return None, None, None
def create_confidence_chart(probabilities, class_names):
"""Create confidence chart using Plotly"""
fig = go.Figure(data=[
go.Bar(
x=class_names,
y=probabilities,
marker_color=['#dc3545', '#28a745'],
text=[f'{p:.1%}' for p in probabilities],
textposition='auto',
)
])
fig.update_layout(
title="Classification Confidence",
xaxis_title="Site Quality",
yaxis_title="Confidence",
yaxis=dict(range=[0, 1]),
showlegend=False,
height=400,
template="plotly_white"
)
return fig
def create_quality_metrics_chart(predicted_class, confidence):
"""Create quality metrics visualization"""
if predicted_class == 1: # Good
quality_score = confidence * 100
color = '#28a745'
status = 'ACCEPTED'
else: # Bad
quality_score = (1 - confidence) * 100
color = '#dc3545'
status = 'REJECTED'
fig = go.Figure(go.Indicator(
mode="gauge+number+delta",
value=quality_score,
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': f"Quality Score
{status}"},
delta={'reference': 80},
gauge={
'axis': {'range': [None, 100]},
'bar': {'color': color},
'steps': [
{'range': [0, 50], 'color': "lightgray"},
{'range': [50, 80], 'color': "yellow"},
{'range': [80, 100], 'color': "lightgreen"}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 90
}
}
))
fig.update_layout(height=400)
return fig
def analyze_site_quality(predicted_class, confidence):
"""Analyze site quality and provide detailed feedback"""
class_names = ['Bad', 'Good']
predicted_label = class_names[predicted_class]
if predicted_class == 1: # Good site
analysis = {
'status': 'ACCEPTED â
',
'color': 'result-good',
'icon': 'â
',
'message': 'Site installation meets quality standards',
'details': [
'â
Cable assembly appears properly organized',
'â
Equipment installation looks correct',
'â
Overall site organization is acceptable',
'â
No obvious safety violations detected'
],
'recommendations': [
'đ Verify all labels are clearly readable',
'đ§ Double-check all card installations',
'đ Complete final inspection checklist',
'đ¸ Document final installation state'
]
}
else: # Bad site
analysis = {
'status': 'REJECTED â',
'color': 'result-bad',
'icon': 'â',
'message': 'Site installation requires attention',
'details': [
'â Cable organization may need improvement',
'â Equipment installation issues detected',
'â Site organization below standards',
'â Potential safety or quality concerns'
],
'recommendations': [
'đ§ Reorganize cable routing and bundling',
'đ Check all card installations and seating',
'đˇī¸ Verify all labels are present and readable',
'â ī¸ Address any safety violations',
'đ Complete corrective actions before acceptance'
]
}
analysis['confidence'] = confidence
analysis['predicted_label'] = predicted_label
return analysis
def display_inspection_checklist():
"""Display telecom site inspection checklist"""
st.markdown("""
Use this checklist to ensure comprehensive site evaluation:
AI-Powered Telecom Site Quality Inspector
Upload an image or take a photo of the telecom site for quality inspection
Confidence: {analysis['confidence']:.1%}