File size: 12,216 Bytes
61e7b06
39a5cd5
61e7b06
 
52de8f8
 
e26711e
39a5cd5
 
 
e26711e
39a5cd5
 
 
 
 
 
cc5c9eb
39a5cd5
 
 
 
61e7b06
 
e26711e
 
4c2379f
cc5c9eb
e26711e
4c2379f
 
 
 
e26711e
 
 
 
cc5c9eb
 
 
 
 
 
 
 
52de8f8
 
4c2379f
 
 
 
 
cc5c9eb
4c2379f
 
 
 
 
e26711e
 
 
39a5cd5
 
 
74f3fe5
cc5c9eb
39a5cd5
4c2379f
 
 
74f3fe5
4c2379f
 
e26711e
4c2379f
e26711e
39a5cd5
 
 
4c2379f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e26711e
 
 
4c2379f
e26711e
 
 
 
61e7b06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74f3fe5
 
61e7b06
 
 
 
74f3fe5
61e7b06
 
 
 
 
 
e26711e
61e7b06
e26711e
61e7b06
 
 
 
 
 
 
 
 
 
 
 
e26711e
 
61e7b06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e26711e
 
61e7b06
 
 
 
 
 
 
 
 
 
52de8f8
61e7b06
 
 
 
 
 
 
52de8f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61e7b06
 
 
 
 
 
 
52de8f8
61e7b06
 
 
 
52de8f8
 
 
 
 
 
61e7b06
 
 
 
52de8f8
 
61e7b06
 
52de8f8
61e7b06
 
 
e26711e
 
 
 
cc5c9eb
e26711e
cc5c9eb
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Utility functions for data processing and API operations
"""

import io
import json
import time
import requests
import numpy as np
import pandas as pd
from typing import Dict, Any, List, Optional
from config.settings import (
    API_BASE_URL, 
    API_VALIDATION_ENDPOINT, 
    API_TIMEOUT, 
    MAX_RETRIES
)
from utils.encryption import encrypt_api_key
from utils.logging_config import get_logger, log_api_request, log_api_response

# Initialize logger
logger = get_logger(__name__)


def validate_api_key_with_server(api_key: str) -> Dict[str, Any]:
    """
    Validate API key with server using real API call
    The API key is encrypted before being sent for validation
    Returns dict with 'valid' boolean, 'message' string, and 'response_time'
    
    Expected response format:
    Success: {"message": "Api Credentials Validated Successfully", "status": "success", "data": {"isValid": true}}
    Error: {"message": "Invalid or revoked API key", "status": "error"}
    """
    if not api_key:
        return {"valid": False, "message": "No API key provided", "response_time": 0}
    
    # Encrypt the API key before sending
    try:
        encrypted_api_key = encrypt_api_key(api_key)
        if encrypted_api_key is None:
            return {"valid": False, "message": "Failed to encrypt API key", "response_time": 0}
    except Exception as e:
        return {"valid": False, "message": f"Encryption error: {str(e)}", "response_time": 0}
    
    # Check if requests library is available
    if requests is None:
        return {"valid": False, "message": "requests library not installed", "response_time": 0}
    
    # Construct the full validation URL
    validation_url = f"{API_BASE_URL}/{API_VALIDATION_ENDPOINT}"
    
    # Prepare headers with encrypted API key
    headers = {
        "Content-Type": "application/json",
        "User-Agent": "Syncora-Client/1.0"
    }
    
    start_time = time.time()
    
    try:
        # Log API request details
        log_api_request(logger, "POST", validation_url, 
                       {"operation": "api_key_validation"})
        
        # Make the API call with encrypted key
        validation_payload = {"apiKey": encrypted_api_key}
        response = requests.post(
            validation_url,
            headers=headers,
            json=validation_payload,
            timeout=API_TIMEOUT
        )
        
        response_time = round(time.time() - start_time, 2)
        
        # Log API response
        log_api_response(logger, response.status_code, response_time, response.status_code == 200)
        
        # Parse response
        try:
            response_data = response.json()
        except ValueError:
            return {
                "valid": False, 
                "message": f"Invalid JSON response from server (status: {response.status_code})", 
                "response_time": response_time
            }
        
        # Check if request was successful
        if response.status_code == 200:
            # Check the response format
            if response_data.get("status") == "success" and response_data.get("data", {}).get("isValid"):
                return {
                    "valid": True,
                    "message": response_data.get("message", "API key validated successfully"),
                    "response_time": response_time,
                    "tier": response_data.get("data", {}).get("tier", "production")
                }
            else:
                return {
                    "valid": False,
                    "message": response_data.get("message", "API key validation failed"),
                    "response_time": response_time
                }
        else:
            # Handle error responses
            error_message = response_data.get("message", f"HTTP {response.status_code} error")
            return {
                "valid": False,
                "message": error_message,
                "response_time": response_time
            }
            
    except requests.exceptions.Timeout:
        return {
            "valid": False, 
            "message": f"Request timeout after {API_TIMEOUT} seconds", 
            "response_time": round(time.time() - start_time, 2)
        }
    except requests.exceptions.ConnectionError:
        return {
            "valid": False, 
            "message": "Could not connect to API server", 
            "response_time": round(time.time() - start_time, 2)
        }
    except requests.exceptions.RequestException as e:
        return {
            "valid": False, 
            "message": f"Request failed: {str(e)}", 
            "response_time": round(time.time() - start_time, 2)
        }
    except Exception as e:
        return {
            "valid": False, 
            "message": f"Validation error: {str(e)}", 
            "response_time": round(time.time() - start_time, 2)
        }


def process_uploaded_file(uploaded_file) -> Dict[str, Any]:
    """Process uploaded file and return file information"""
    if uploaded_file is None:
        return {"success": False, "error": "No file uploaded"}
        
    try:
        file_info = {
            "success": True,
            "name": uploaded_file.name,
            "type": uploaded_file.type,
            "size_kb": len(uploaded_file.getvalue()) / 1024
        }
        
        if uploaded_file.type == "text/csv":
            df = pd.read_csv(uploaded_file)
            file_info["preview"] = df.head(3)
            file_info["preview_type"] = "dataframe"
            file_info["num_rows"] = len(df)
            file_info["size_bytes"] = len(uploaded_file.getvalue())
        elif uploaded_file.type in ["text/plain", "text/markdown"]:
            content = str(uploaded_file.read(), "utf-8")
            file_info["preview"] = content[:300] + "..." if len(content) > 300 else content
            file_info["preview_type"] = "text"
            file_info["size_bytes"] = len(uploaded_file.getvalue())
            
        return file_info
    except Exception as e:
        return {"success": False, "error": f"Error processing file: {str(e)}"}


def generate_sample_data(num_records: int, output_format: str, api_key: Optional[str] = None) -> Dict[str, Any]:
    """Generate sample data in the specified format"""
    
    data = []
    for i in range(num_records):
        record = {
            "id": i + 1,
            "question": f"What is the main concept discussed in section {i+1}?",
            "answer": f"Section {i+1} covers key insights about data processing and analysis methodologies, providing comprehensive explanations of the underlying principles.",
            "context": f"This is the contextual information extracted from document chunk {i+1}",
            "confidence_score": round(np.random.uniform(0.85, 0.99), 3),
            "source": f"document_chunk_{i+1}",
            "metadata": {
                "chunk_id": i + 1,
                "processing_time": round(np.random.uniform(0.1, 2.5), 2),
                "token_count": np.random.randint(150, 500),
                "api_key_used": bool(api_key)  # Track if API key was used
            }
        }
        data.append(record)
    
    if output_format == "tabular":
        # Flatten for tabular format
        flattened_data = []
        for record in data:
            flat_record = {
                "ID": record["id"],
                "Question": record["question"],
                "Answer": record["answer"],
                "Context": record["context"],
                "Confidence": record["confidence_score"],
                "Source": record["source"],
                "Chunk_ID": record["metadata"]["chunk_id"],
                "Processing_Time": record["metadata"]["processing_time"],
                "Token_Count": record["metadata"]["token_count"],
                "API_Authenticated": record["metadata"]["api_key_used"]
            }
            flattened_data.append(flat_record)
        return {"format": "tabular", "data": flattened_data}
    else:  # JSONL format
        return {"format": "jsonl", "data": data}


def calculate_generation_metrics(generated_data: Dict[str, Any]) -> Dict[str, Any]:
    """Calculate metrics from generated data"""
    data = generated_data["data"]
    format_type = generated_data.get("format", "tabular")  # Default to tabular
    
    metrics = {
        "total_records": len(data),
        "format": format_type.upper()
    }
    
    if format_type == "tabular":
        # Handle both traditional format and DataFrame-based format
        if data and isinstance(data[0], dict):
            # Traditional format with confidence and token fields
            if "Confidence" in data[0]:
                metrics["avg_confidence"] = np.mean([r.get("Confidence", 0.85) for r in data])
            else:
                metrics["avg_confidence"] = 0.85  # Default confidence
                
            if "Token_Count" in data[0]:
                metrics["total_tokens"] = sum([r.get("Token_Count", 10) for r in data])
            else:
                metrics["total_tokens"] = len(data) * 10  # Estimate
                
            # Check if API was authenticated
            if data and "API_Authenticated" in data[0]:
                metrics["api_authenticated"] = data[0]["API_Authenticated"]
        else:
            # DataFrame-based format or simple records
            metrics["avg_confidence"] = 0.85  # Default confidence
            metrics["total_tokens"] = len(data) * 10  # Estimate based on record count
            metrics["api_authenticated"] = True  # Assume authenticated if we got data
            
    else:  # JSONL format
        if data and isinstance(data[0], dict):
            if "confidence_score" in data[0]:
                metrics["avg_confidence"] = np.mean([r.get("confidence_score", 0.85) for r in data])
            else:
                metrics["avg_confidence"] = 0.85
                
            if "metadata" in data[0] and "token_count" in data[0]["metadata"]:
                metrics["total_tokens"] = sum([r.get("metadata", {}).get("token_count", 10) for r in data])
            else:
                metrics["total_tokens"] = len(data) * 10
                
            # Check if API was authenticated
            if data and "metadata" in data[0] and "api_key_used" in data[0]["metadata"]:
                metrics["api_authenticated"] = data[0]["metadata"]["api_key_used"]
        else:
            metrics["avg_confidence"] = 0.85
            metrics["total_tokens"] = len(data) * 10
            metrics["api_authenticated"] = True
    
    return metrics


def create_download_data(generated_data: Dict[str, Any]) -> Dict[str, Any]:
    """Prepare data for download in various formats"""
    data = generated_data["data"]
    format_type = generated_data.get("format", "tabular")  # Default to tabular
    
    downloads = {}
    
    if format_type == "tabular":
        # Check if we have a DataFrame available
        if "dataframe" in generated_data:
            df = generated_data["dataframe"]
        else:
            df = pd.DataFrame(data)
            
        downloads["csv"] = df.to_csv(index=False)
        
        # For Excel download
        buffer = io.BytesIO()
        with pd.ExcelWriter(buffer, engine='openpyxl') as writer:
            df.to_excel(writer, index=False, sheet_name='Generated Data')
        downloads["excel"] = buffer.getvalue()
        
    else:  # JSONL format
        downloads["jsonl"] = "\n".join([json.dumps(record) for record in data])
    
    return downloads


def get_api_headers(api_key: str) -> Dict[str, str]:
    """
    Get headers for API calls including the encrypted API key
    """
    try:
        encrypted_api_key = encrypt_api_key(api_key)
        if encrypted_api_key is None:
            raise ValueError("Failed to encrypt API key")
        
        return {
            "x-api-key": encrypted_api_key,
            "Content-Type": "application/json",
            "User-Agent": "Syncora-Client/1.0"
        }
    except Exception as e:
        # If encryption fails, raise an error rather than sending unencrypted key
        raise ValueError(f"Failed to prepare API headers: {str(e)}")