tabular-generation-test / src /components /data_generation.py
Khushal-kreeda
fix: minor fix
d428254
Raw History Blame Contribute Delete
33.1 kB
"""
Data generation components and UI
"""
import io
import json
import pandas as pd
import requests
import streamlit as st
import time
from config.settings import (
API_BASE_URL,
DEFAULT_NUM_RECORDS,
MAX_RECORDS,
DEFAULT_TEMPERATURE,
DEFAULT_MAX_TOKENS,
OUTPUT_FORMATS,
PROGRESS_STEPS,
GENERATION_API_ENDPOINT,
API_TIMEOUT
)
from utils.aws_s3 import download_file_from_s3_url
from utils.data_processing import (
validate_api_key_with_server,
generate_sample_data,
calculate_generation_metrics,
create_download_data,
get_api_headers
)
from utils.session_state import clear_api_state
from utils.logging_config import get_logger, log_api_request, log_api_response, log_generation_metrics
# Initialize logger
logger = get_logger(__name__)
def render_api_key_input():
"""Render API key input and validation"""
api_key = st.text_input(
"πŸ”‘ Syncora API Key",
type="password",
placeholder="Enter your API key (e.g., sync-xxxxxxxxxxxx)",
help="Get your API key from the Syncora dashboard. Your key is encrypted before transmission for security.",
key="api_key_input"
)
# Validate API key button
col_validate, col_status = st.columns([1, 2])
with col_validate:
validate_clicked = st.button(
"πŸ” Validate",
key="validate_api_key",
help="Validate API key with server using encrypted transmission",
use_container_width=True
)
# Handle validation
if validate_clicked and api_key:
with st.spinner("Validating API key (encrypting and sending securely)..."):
validation_result = validate_api_key_with_server(api_key)
st.session_state.api_validation = validation_result
if validation_result.get("valid", False):
st.session_state.validated_api_key = api_key
st.session_state.validation_attempted = True
st.rerun() # Force rerun to update UI immediately
elif validate_clicked and not api_key:
st.session_state.api_validation = {"valid": False, "message": "Please enter an API key first"}
st.session_state.validation_attempted = True
# Reset validation status when key changes
if api_key != st.session_state.get('last_api_key', ''):
st.session_state.last_api_key = api_key
# Reset validation status when key changes (but don't show error)
if not api_key:
st.session_state.api_validation = {"valid": False, "message": ""}
st.session_state.validation_attempted = False
elif api_key != st.session_state.get('validated_api_key', ''):
# Key changed from a previously validated key
st.session_state.api_validation = {"valid": False, "message": ""}
st.session_state.validation_attempted = False
# Display validation status - only if validation was attempted
with col_status:
if (hasattr(st.session_state, 'validation_attempted') and
st.session_state.validation_attempted and
hasattr(st.session_state, 'api_validation') and
st.session_state.api_validation):
validation = st.session_state.api_validation
if validation["valid"]:
message = validation["message"]
if "response_time" in validation:
message += f" ({validation['response_time']}s)"
st.markdown(f'<div class="status-indicator status-valid">βœ… {message}</div>',
unsafe_allow_html=True)
else:
st.markdown(f'<div class="status-indicator status-invalid">❌ {validation["message"]}</div>',
unsafe_allow_html=True)
else:
# Show neutral state when no validation attempted
st.markdown('<div class="status-indicator status-pending">πŸ’‘ Click validate to check API key</div>',
unsafe_allow_html=True)
return api_key
def render_generation_settings():
"""Render generation settings"""
# Number of Records
num_records = st.number_input(
"Number of Records",
min_value=1,
max_value=MAX_RECORDS,
value=DEFAULT_NUM_RECORDS,
step=5,
help="Number of data records to generate"
)
return {
"num_records": num_records,
"temperature": DEFAULT_TEMPERATURE,
"max_tokens": DEFAULT_MAX_TOKENS,
"include_metadata": True
}
def render_generation_progress():
"""Show generation progress with real API call tracking"""
# Create placeholder for real-time status updates
progress_placeholder = st.empty()
status_placeholder = st.empty()
# Initial status
with progress_placeholder:
st.info("πŸ€– Initializing data generation request...")
return progress_placeholder, status_placeholder
def render_results_display(generated_data, num_records):
"""Display generation results"""
# Get actual record count from the data
actual_records = generated_data.get("records_count", num_records)
if "dataframe" in generated_data:
actual_records = len(generated_data["dataframe"])
elif "data" in generated_data:
actual_records = len(generated_data["data"])
st.success(f"βœ… Successfully generated {actual_records} records in {st.session_state.output_format.upper()} format!")
# Display results
st.markdown("### πŸ“Š Generated Results")
if generated_data.get("format") == "tabular" or "dataframe" in generated_data:
# Check if we have a DataFrame or need to create one
if "dataframe" in generated_data:
df_results = generated_data["dataframe"]
else:
df_results = pd.DataFrame(generated_data["data"])
# Display the DataFrame
st.dataframe(df_results, use_container_width=True, height=400)
# Download buttons section
st.markdown("### πŸ“₯ Download Options")
# If we have the original file content from S3, use it for download
if "file_content" in generated_data and "filename" in generated_data:
# Original file download
original_filename = generated_data["filename"]
file_extension = original_filename.split('.')[-1].lower()
col_original, col_csv, col_excel = st.columns(3)
with col_original:
st.download_button(
f"πŸ“₯ Download Original ({file_extension.upper()})",
generated_data["file_content"],
original_filename,
f"application/{file_extension}",
use_container_width=True,
help="Download the file exactly as generated by the API"
)
# CSV download
with col_csv:
csv_data = df_results.to_csv(index=False)
st.download_button(
"πŸ“₯ Download CSV",
csv_data,
f"syncora_data_{int(time.time())}.csv",
"text/csv",
use_container_width=True,
help="Download as CSV format"
)
# Excel download
with col_excel:
excel_buffer = io.BytesIO()
with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer:
df_results.to_excel(writer, index=False, sheet_name='Generated Data')
excel_data = excel_buffer.getvalue()
st.download_button(
"πŸ“₯ Download Excel",
excel_data,
f"syncora_data_{int(time.time())}.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
use_container_width=True,
help="Download as Excel format"
)
else:
# Fallback to creating download data
download_data = create_download_data(generated_data)
col_csv, col_excel = st.columns(2)
with col_csv:
st.download_button(
"πŸ“₯ Download CSV",
download_data["csv"],
f"syncora_data_{int(time.time())}.csv",
"text/csv",
use_container_width=True
)
with col_excel:
st.download_button(
"πŸ“₯ Download Excel",
download_data["excel"],
f"syncora_data_{int(time.time())}.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
use_container_width=True
)
# Show S3 URL if available
if "s3_url" in generated_data:
st.markdown("### πŸ”— Direct Access")
st.info(f"**Generated File URL:** {generated_data['s3_url']}")
else: # JSONL format
# Show preview
jsonl_preview = []
for record in generated_data["data"][:5]: # Show first 5 records
jsonl_preview.append(json.dumps(record, indent=2))
st.code("\n\n".join(jsonl_preview), language="json")
if len(generated_data["data"]) > 5:
st.info(f"Showing first 5 records out of {len(generated_data['data'])} total records")
# Download JSONL
download_data = create_download_data(generated_data)
st.download_button(
"πŸ“₯ Download JSONL",
download_data["jsonl"],
f"syncora_data_{int(time.time())}.jsonl",
"application/json",
use_container_width=True
)
def render_generation_metrics(generated_data):
"""Display generation metrics"""
st.markdown("### πŸ“ˆ Generation Metrics")
metrics = calculate_generation_metrics(generated_data)
col_met1, col_met2, col_met3, col_met4 = st.columns(4)
with col_met1:
st.metric("Records", metrics["total_records"])
with col_met2:
st.metric("Avg Confidence", f"{metrics['avg_confidence']:.2f}")
with col_met3:
format_display = metrics.get("format", "tabular").title()
st.metric("Format", format_display)
with col_met4:
# Show file size if available
if "file_content" in generated_data:
file_size_mb = len(generated_data["file_content"]) / (1024 * 1024)
st.metric("File Size", f"{file_size_mb:.2f} MB")
elif "api_authenticated" in metrics:
status = "βœ… Yes" if metrics["api_authenticated"] else "❌ No"
st.metric("API Auth", status)
else:
st.metric("Total Tokens", f"{metrics.get('total_tokens', 0):,}")
# Additional info row if file was downloaded from S3
if generated_data.get("s3_url"):
st.markdown("---")
col_extra1, col_extra2, col_extra3 = st.columns(3)
with col_extra1:
if "filename" in generated_data:
st.metric("Original File", generated_data["filename"])
with col_extra2:
st.metric("Source", "S3 Download")
with col_extra3:
if metrics.get("total_tokens"):
st.metric("Total Tokens", f"{metrics['total_tokens']:,}")
elif metrics.get("api_authenticated"):
st.markdown("---")
col_extra1, col_extra2 = st.columns(2)
with col_extra1:
st.metric("Total Tokens", f"{metrics.get('total_tokens', 0):,}")
with col_extra2:
st.metric("Auth Method", "x-api-key")
def render_api_key_validation_step():
"""Render API key validation as the first required step"""
# Check if we already have a validated API key
is_complete = (st.session_state.get('api_validation', {}).get('valid', False) and
st.session_state.get('validated_api_key', ''))
if is_complete:
st.markdown('<h3 class="section-title step-complete">πŸ”‘ Step 1: API Key Validation βœ…</h3>', unsafe_allow_html=True)
st.success(f"βœ… API Key validated successfully!")
# Show option to change API key
if st.button("πŸ”„ Change API Key", help="Use a different API key", key="change_api_key_btn"):
# Clear all API-related session state
clear_api_state()
st.rerun()
return True
else:
st.markdown('<h3 class="section-title step-incomplete">πŸ”‘ Step 1: API Key Validation</h3>', unsafe_allow_html=True)
# Show API key input and validation
render_api_key_input()
# Return the current validation state from session state, ensuring it's a boolean
return bool(st.session_state.get('api_validation', {}).get('valid', False) and
st.session_state.get('validated_api_key', ''))
def call_generation_api(file_link, config, api_key, file_metadata=None, progress_placeholder=None, status_placeholder=None):
"""
Call the generation API with file link and configuration
Args:
file_link (str): AWS S3 link to the uploaded file
config (dict): All configuration settings including generation settings
api_key (str): Validated API key
file_metadata (dict): File metadata including size and row count
Returns:
dict: Generated data response
"""
# Construct API URL and payload
api_url = f"{API_BASE_URL}/{GENERATION_API_ENDPOINT}"
payload = {
"fileUrl": file_link,
"type": "Tabular",
"numberOfRows": config.get("num_rows", 100)
}
# Add file metadata if available
if file_metadata:
payload["fileSizeBytes"] = file_metadata.get("file_size_bytes", 0)
payload["sourceFileRows"] = file_metadata.get("num_rows", 0)
st.info(f"πŸ“Š Including file metadata: {file_metadata.get('num_rows', 0)} rows, {file_metadata.get('file_size_bytes', 0)} bytes")
# Add target column if specified
if config.get("target_column", "").strip():
payload["targetColumn"] = config["target_column"].strip()
# Prepare encrypted headers
try:
headers = get_api_headers(api_key)
except ValueError as e:
return {"success": False, "error": f"Failed to prepare headers: {str(e)}"}
# Make API call
try:
# Log API request
log_api_request(logger, "POST", api_url, {
"numberOfRows": payload.get('numberOfRows'),
"type": payload.get('type'),
"targetColumn": payload.get('targetColumn')
})
# Update progress if available
if status_placeholder:
with status_placeholder:
st.info("🌐 Making API call...")
st.info("πŸ”„ Making API call...")
start_time = time.time()
response = requests.post(api_url, json=payload, headers=headers, timeout=API_TIMEOUT)
response_time = time.time() - start_time
# Log API response
log_api_response(logger, response.status_code, response_time, response.status_code == 200)
# Handle response
if response.status_code == 200:
try:
result = response.json()
# Update progress
if status_placeholder:
with status_placeholder:
st.success("βœ… API call successful!")
st.success("βœ… API call successful!")
# Log successful response for monitoring
logger.info(f"Generation API returned {len(result.keys())} result keys")
# Check for different possible URL keys in the response
# First check if there's a nested data object
data_obj = result.get("data", result)
url_keys = ["fileUrl", "s3Url", "downloadUrl", "file_url", "s3_url", "download_url", "url"]
s3_url = None
# Check in the data object first, then in the main result
for obj in [data_obj, result]:
for key in url_keys:
if key in obj:
s3_url = obj[key]
logger.info(f"Generated file URL found: {key}")
st.info(f"πŸ“Ž Found generated file URL")
break
if s3_url:
break
if s3_url:
# Update progress
if status_placeholder:
with status_placeholder:
st.info("πŸ“₯ Downloading generated file from S3...")
st.info("πŸ“₯ Downloading generated file from S3...")
# Print S3 URL to console
logger.info(f"Attempting to download from S3 URL")
# Try to download the file from S3
download_result = download_file_from_s3_url(s3_url)
if download_result["success"]:
# Parse the downloaded file content
try:
file_content = download_result["content"]
filename = download_result["filename"]
st.success(f"βœ… Downloaded file: {filename}")
# Determine file type and parse accordingly
if filename.lower().endswith('.csv'):
df = pd.read_csv(io.BytesIO(file_content))
elif filename.lower().endswith(('.xlsx', '.xls')):
df = pd.read_excel(io.BytesIO(file_content))
elif filename.lower().endswith('.json'):
df = pd.read_json(io.BytesIO(file_content))
else:
# Try CSV as default
df = pd.read_csv(io.BytesIO(file_content))
# Convert DataFrame to list of dictionaries
data_records = df.to_dict('records')
# Update final progress
if progress_placeholder:
with progress_placeholder:
st.success("πŸŽ‰ Data generation completed successfully!")
if status_placeholder:
with status_placeholder:
st.success(f"βœ… Generated {len(data_records)} records successfully!")
st.info(f"πŸ“Š Parsed {len(data_records)} records from downloaded file")
return {
"data": data_records,
"dataframe": df,
"success": True,
"records_count": len(data_records),
"api_response": result,
"s3_url": s3_url,
"filename": filename,
"file_content": file_content,
"format": "tabular"
}
except Exception as parse_error:
st.error(f"❌ Failed to parse downloaded file: {str(parse_error)}")
if st.session_state.get('debug_mode', False):
logger.debug(f"Parse error: {str(parse_error)}")
return {
"success": False,
"error": f"Failed to parse downloaded file: {str(parse_error)}",
"api_response": result
}
else:
# S3 download failed, try direct HTTP download as fallback
st.warning("⚠️ S3 download failed, trying direct HTTP download...")
logger.warning(f"S3 download failed: {download_result['error']}")
logger.info("Attempting direct HTTP download...")
try:
# Try direct HTTP request to the S3 URL
response = requests.get(s3_url, timeout=60)
if response.status_code == 200:
file_content = response.content
filename = s3_url.split('/')[-1]
st.success(f"βœ… Downloaded via HTTP: {filename}")
# Parse the file content
if filename.lower().endswith('.csv'):
df = pd.read_csv(io.BytesIO(file_content))
elif filename.lower().endswith(('.xlsx', '.xls')):
df = pd.read_excel(io.BytesIO(file_content))
elif filename.lower().endswith('.json'):
df = pd.read_json(io.BytesIO(file_content))
else:
# Try CSV as default
df = pd.read_csv(io.BytesIO(file_content))
# Convert DataFrame to list of dictionaries
data_records = df.to_dict('records')
st.info(f"πŸ“Š Parsed {len(data_records)} records from downloaded file")
return {
"data": data_records,
"dataframe": df,
"success": True,
"records_count": len(data_records),
"api_response": result,
"s3_url": s3_url,
"filename": filename,
"file_content": file_content,
"format": "tabular"
}
else:
st.error(f"❌ HTTP download failed with status {response.status_code}")
logger.error(f"HTTP download failed: {response.status_code}")
return {
"success": False,
"error": f"Both S3 and HTTP download failed. S3 error: {download_result['error']}, HTTP status: {response.status_code}",
"api_response": result
}
except Exception as http_error:
st.error(f"❌ Direct download failed: {str(http_error)}")
logger.error(f"HTTP download error: {str(http_error)}")
return {
"success": False,
"error": f"Both S3 and HTTP download failed. S3 error: {download_result['error']}, HTTP error: {str(http_error)}",
"api_response": result
}
else:
# No S3 URL found, check if data is directly in response
# Check both the main result and nested data object
data_obj = result.get("data", result)
# Look for data in both locations
direct_data = None
if "data" in result and isinstance(result["data"], list):
direct_data = result["data"]
elif "data" in data_obj and isinstance(data_obj["data"], list):
direct_data = data_obj["data"]
elif isinstance(data_obj, list):
direct_data = data_obj
if direct_data and len(direct_data) > 0:
st.info("πŸ“Š Using data directly from API response")
return {
"data": direct_data,
"success": True,
"records_count": len(direct_data),
"api_response": result,
"format": "tabular"
}
else:
st.warning("⚠️ No file URL or data found in API response")
return {
"success": False,
"error": "No file URL or data found in API response",
"api_response": result
}
except json.JSONDecodeError as e:
st.error(f"❌ Failed to parse JSON response: {str(e)}")
return {
"success": False,
"error": f"Invalid JSON response: {str(e)}",
"raw_response": response.text
}
elif response.status_code == 401:
st.error("❌ Authentication failed - Invalid API key")
return {
"success": False,
"error": "Invalid API key. Please check your credentials.",
"status_code": 401,
"response_text": response.text
}
elif response.status_code == 400:
st.error(f"❌ Bad request - Check your input data")
return {
"success": False,
"error": f"Bad request: {response.text}",
"status_code": 400,
"response_text": response.text
}
else:
st.error(f"❌ API error {response.status_code}")
return {
"success": False,
"error": f"API error {response.status_code}: {response.text}",
"status_code": response.status_code,
"response_text": response.text
}
except requests.exceptions.Timeout:
st.error(f"❌ Request timed out after {API_TIMEOUT} seconds")
return {"success": False, "error": f"Request timed out after {API_TIMEOUT} seconds"}
except requests.exceptions.ConnectionError:
st.error("❌ Could not connect to API server")
return {"success": False, "error": "Could not connect to API server. Check your internet connection."}
except Exception as e:
st.error(f"❌ Unexpected error: {str(e)}")
return {"success": False, "error": f"Unexpected error: {str(e)}"}
def render_generation_and_results(file_link, config, enabled=True):
"""Render generation button and results display"""
if enabled:
st.markdown('<h3 class="section-title step-incomplete">πŸš€ Step 4: Generate Data</h3>', unsafe_allow_html=True)
else:
st.markdown('<h3 class="section-title step-disabled">πŸš€ Step 4: Generate Data πŸ”’</h3>', unsafe_allow_html=True)
if not enabled:
st.info("πŸ”’ Complete Steps 1-3 to enable data generation")
st.button(
"πŸš€ Generate Data",
use_container_width=True,
type="primary",
disabled=True
)
# Show placeholder results area
st.markdown("**Results will appear here after generation**")
st.empty()
return
# Generation button
generate_clicked = st.button(
f"πŸš€ Generate {st.session_state.output_format.upper()} Data",
use_container_width=True,
type="primary",
help="Generate synthetic data using your uploaded file and configuration"
)
# Add timeout info
st.info("⏱️ Data generation may take up to 30 minutes depending on file size and complexity. Please be patient!")
# Handle generation
if generate_clicked:
# Show initial progress
progress_placeholder, status_placeholder = render_generation_progress()
# Get validated API key
api_key = st.session_state.get('validated_api_key', '')
# Update status
with status_placeholder:
st.info("πŸ” Preparing API request...")
# Get file metadata from session state
file_metadata = None
# Look for file metadata in session state
for key in st.session_state.keys():
if isinstance(key, str) and key.startswith('file_metadata_'):
file_metadata = st.session_state[key]
break
# Update status
with status_placeholder:
st.info("πŸ“‘ Sending request to generation API...")
# Call API with file link, configuration, and file metadata
result = call_generation_api(file_link, config, api_key, file_metadata, progress_placeholder, status_placeholder)
# If API call failed with 403/401 and we have a presigned URL, try with that
if (not result.get("success", False) and
result.get("status_code") in [401, 403] and
"file_url" in st.session_state):
# Look for presigned URL in session state
presigned_key = f"{st.session_state.get('current_file_key', 'file_url')}_presigned"
if presigned_key in st.session_state:
presigned_url = st.session_state[presigned_key]
st.info("πŸ”„ Retrying with authenticated URL...")
logger.info("Retrying API call with presigned URL")
# Retry with presigned URL
result = call_generation_api(presigned_url, config, api_key, file_metadata, progress_placeholder, status_placeholder)
# Handle API response
if result.get("success", False):
st.session_state.generated_data = result
st.success("βœ… Data generation completed successfully!")
# Display results
render_results_display(result, result.get("records_count", config.get("num_rows", 100)))
# Show metrics
render_generation_metrics(result)
else:
# Clear progress indicators on error
if progress_placeholder:
with progress_placeholder:
pass # Clear the placeholder
if status_placeholder:
with status_placeholder:
pass # Clear the placeholder
# Handle API errors
error_message = result.get("error", "Unknown error occurred")
st.error(f"❌ Generation failed: {error_message}")
# Print detailed error information to console
logger.error(f"Generation API error: {error_message}")
# Log additional context for debugging
if "status_code" in result:
logger.error(f"Status Code: {result['status_code']}")
if "api_response" in result and isinstance(result["api_response"], dict):
logger.debug(f"API Response Keys: {list(result['api_response'].keys())}")
# Show minimal error info in UI with option to see more
with st.expander("πŸ” Error Details", expanded=False):
st.markdown("**Summary:**")
st.text(error_message)
if "status_code" in result:
st.markdown(f"**Status Code:** {result['status_code']}")
st.markdown("*Enable Debug Mode in sidebar for detailed console logs*")
# Show previous results if they exist
elif st.session_state.get('generated_data') and st.session_state.generated_data.get("success", False):
st.markdown("**Previous Generation Results:**")
render_results_display(st.session_state.generated_data, st.session_state.generated_data.get("records_count", config.get("num_rows", 100)))
render_generation_metrics(st.session_state.generated_data)