Download src/utils/data_processing.py from Khushal-ag/tabular-generation-test: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/spaces/Khushal-ag/tabular-generation-test/resolve/main/src/utils/data_processing.py
- Command line
-
hf download hf://spaces/Khushal-ag/tabular-generation-test/src/utils/data_processing.py
-
curl -L -o data_processing.py https://huggingface.co/spaces/Khushal-ag/tabular-generation-test/resolve/main/src/utils/data_processing.py
12.2 kB
| """ | |
| 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)}") | |