import requests import json import time from typing import Dict, Any, Optional, Union, List import logging import streamlit as st from app.config import AppConfig class APIClient: """Client for interacting with the Email Spam Classifier API""" def __init__(self, base_url: str = None): self.config = AppConfig() self.base_url = base_url or self.config.API_BASE_URL self.timeout = self.config.API_TIMEOUT # Set up logging logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger("api_client") # Validate API connection self._validate_connection() def _validate_connection(self) -> bool: """Validate connection to the API""" try: response = self._make_request("GET", "/health") if response.get("status") != "ok": self.logger.warning("API responded but health check failed") return False self.logger.info("Successfully connected to API") return True except Exception as e: self.logger.error(f"Failed to connect to API: {str(e)}") return False def _make_request( self, method: str, endpoint: str, data: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, retry_count: int = 3 ) -> Dict[str, Any]: """Make a request to the API with retry logic""" url = f"{self.base_url}{endpoint}" default_headers = { "Content-Type": "application/json", "Accept": "application/json", "User-Agent": f"SpamClassifier-StreamlitApp/{self.config.APP_VERSION}" } if headers: default_headers.update(headers) for attempt in range(retry_count): try: response = requests.request( method=method, url=url, json=data, params=params, headers=default_headers, timeout=self.timeout ) response.raise_for_status() return response.json() except requests.exceptions.HTTPError as e: if response.status_code == 429: # Rate limit retry_after = int(response.headers.get("Retry-After", 1)) self.logger.warning(f"Rate limited, retrying in {retry_after}s") time.sleep(retry_after) continue # Try to get error details from JSON response try: error_detail = response.json().get("detail", str(e)) except: error_detail = str(e) self.logger.error(f"HTTP error: {error_detail}") raise Exception(f"API error: {error_detail}") except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e: if attempt < retry_count - 1: wait_time = 2 ** attempt # Exponential backoff self.logger.warning(f"Connection error, retrying in {wait_time}s: {str(e)}") time.sleep(wait_time) continue self.logger.error(f"Connection failed after {retry_count} attempts: {str(e)}") raise Exception(f"Failed to connect to API: {str(e)}") except Exception as e: self.logger.error(f"Unexpected error: {str(e)}") raise Exception(f"Unexpected error: {str(e)}") def get_health(self) -> Dict[str, Any]: """Get API health status""" return self._make_request("GET", "/health") def classify_email(self, content: str) -> Dict[str, Any]: """ Classify email content as spam or ham Args: content: The email content to classify Returns: Dict containing classification results """ # The API endpoint expects a JSON object with a 'text' field payload = {"text": content} # Ensure we use 'text' field as required by the API self.logger.info(f"Sending classification request for email") # Make the request to the API response = self._make_request("POST", "/api/v1/classify", data=payload) # st.write(response) # The response contains a nested 'result' object based on the router's response model if "result" in response: return response["result"] return response def batch_classify_emails(self, contents: List[str]) -> List[Dict[str, Any]]: """ Classify multiple email contents as spam or ham Args: contents: List of email contents to classify Returns: List of dictionaries containing classification results """ results = [] # Process each email individually # Note: In a production environment, you might want to implement # a true batch endpoint on your API for better performance for content in contents: try: result = self.classify_email(content) results.append(result) except Exception as e: self.logger.error(f"Error classifying email: {str(e)}") # Add a failed result results.append({ "is_spam": False, "spam_probability": 0.0, "explanation": f"Error during classification: {str(e)}", "error": True }) return results