File size: 5,949 Bytes
f6ea7de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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