Critically analyze the following streamlit python code and provide your insights: import…
- User
Critically analyze the following streamlit python code and provide your insights:
import streamlit as st import os import shutil import cv2 import numpy as np import insightface from insightface.app import FaceAnalysis import tkinter from tkinter import filedialog import math import logging from datetime import datetime from concurrent.futures import ProcessPoolExecutor, as_completed from tqdm import tqdm import warnings import plotly.graph_objects as go from PIL import Image as PILImage import time
warnings.filterwarnings('ignore', category=UserWarning)
class ImageProcessor: def init(self, thumbnails_folder, processed_thumbnails_folder): self.thumbnails_folder = thumbnails_folder self.processed_thumbnails_folder = processed_thumbnails_folder self.face_analyzer = self._initialize_face_analyzer() self._setup_logging() self._ensure_output_directory()
def _initialize_face_analyzer(self): with warnings.catch_warnings(): warnings.simplefilter("ignore") app = FaceAnalysis( name='buffalo_l', providers=['CPUExecutionProvider'] ) app.prepare(ctx_id=-1, det_size=(640, 640)) return app def _setup_logging(self): log_file = f'image_processing_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log' logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler(log_file), logging.StreamHandler() ] ) def _ensure_output_directory(self): if not os.path.exists(self.processed_thumbnails_folder): os.makedirs(self.processed_thumbnails_folder) logging.info(f"Created output directory: {self.processed_thumbnails_folder}") def get_face_orientation(self, face): kps = face.kps left_eye = kps[0] right_eye = kps[1] dy = right_eye[1] - left_eye[1] dx = right_eye[0] - left_eye[0] angle = math.degrees(math.atan2(dy, dx)) if angle < 0: angle += 360 angle_map = {0: 0, 90: 90, 180: 180, 270: 270} nearest_90 = min(angle_map.keys(), key=lambda x: abs((angle - x + 180) % 360 - 180)) return angle_map[nearest_90] def rotate_image(self, image, angle): height, width = image.shape[:2] if angle in [90, 270]: new_width, new_height = height, width else: new_width, new_height = width, height center = (width // 2, height // 2) rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0) if angle == 90: rotation_matrix[0, 2] += (height - width) / 2 rotation_matrix[1, 2] += (height - width) / 2 elif angle == 270: rotation_matrix[0, 2] += (height - width) / 2 rotation_matrix[1, 2] += (width - height) / 2 rotated_image = cv2.warpAffine( image, rotation_matrix, (new_width, new_height), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0) ) return rotated_image def process_thumbnails(self): supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff') image_files = [f for f in os.listdir(self.thumbnails_folder) if f.lower().endswith(supported_formats)] if not image_files: st.error(f"No supported images found in {self.thumbnails_folder}") return successful = 0 failed = 0 # Create container for progress tracking progress_container = st.container() with progress_container: progress_bar = st.progress(0) status_text = st.empty() # Create container for image display image_container = st.container() for idx, image_file in enumerate(image_files): with image_container: st.markdown("---") # Horizontal rule st.markdown(f"**Image {idx + 1}/{len(image_files)}: {image_file}**") col1, col2 = st.columns(2) input_path = os.path.join(self.thumbnails_folder, image_file) output_path = os.path.join(self.processed_thumbnails_folder, f"processed_{image_file}") try: image = cv2.imread(input_path) if image is None: failed += 1 continue # Display original image with col1: st.markdown("**Original Image**") st.image(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), use_container_width=True) faces = self.face_analyzer.get(image) if not faces: cv2.imwrite(output_path, image) with col2: st.markdown("**Processed Image (No rotation needed)**") st.image(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), use_container_width=True) successful += 1 continue face = faces[0] angle = self.get_face_orientation(face) if angle in [90, 180, 270]: image = self.rotate_image(image, angle) # Display processed image with col2: st.markdown(f"**Processed Image (Rotation: {angle}°)**") st.image(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), use_container_width=True) cv2.imwrite(output_path, image) successful += 1 except Exception as e: st.error(f"Error processing {input_path}: {str(e)}") failed += 1 # Update progress progress = (idx + 1) / len(image_files) progress_bar.progress(progress) status_text.text(f"Processing: {idx + 1}/{len(image_files)} images") st.markdown("---") # Final horizontal rule st.success(f"Processing completed: Total: {len(image_files)}, Successful: {successful}, Failed: {failed}") - Assistant