Khushal-kreeda commited on
Commit ·
74f3fe5
1
Parent(s): 52de8f8
fix: updated req body
Browse filesFiles changed (4)
1 unmodified line23456781 unmodified linepandasnumpyaltairopenpyxlPyPDF2python-docxpython-dotenv1 unmodified line2345671 unmodified linepandasnumpyaltairPyPDF2python-docxpython-dotenv
386 unmodified lines3873883893903913923931 unmodified line3953963973983994001 unmodified line4024034044054064074084094104114124134144153 unmodified lines4194204214224234242 unmodified lines427428429430431432433434435105 unmodified lines541542543544545546547548386 unmodified linesst.info("🎯 **Ready to generate!** Click the generate button above.")def call_generation_api(file_link, config, api_key):"""Call the generation API with file link and configuration1 unmodified linefile_link (str): AWS S3 link to the uploaded fileconfig (dict): All configuration settings including generation settingsapi_key (str): Validated API keyReturns:dict: Generated data response1 unmodified line# Construct API URL and payloadapi_url = f"{API_BASE_URL}/{GENERATION_API_ENDPOINT}"payload = {"file_url": file_link,"type": "Tabular","numberOfRows": config.get("num_rows", 100)}# Add target column if specifiedif config.get("target_column", "").strip():payload["TargetColumn"] = config["target_column"].strip()# Prepare encrypted headerstry:3 unmodified lines# Make API calltry:st.info("🔄 Making API call...")response = requests.post(api_url, json=payload, headers=headers, timeout=API_TIMEOUT)2 unmodified linesresult = response.json()# Check if API returns an S3 URL for the generated fileif "file_url" in result or "s3_url" in result or "download_url" in result:# Extract the S3 URL from responses3_url = result.get("file_url") or result.get("s3_url") or result.get("download_url")st.info("📥 Downloading generated file from S3...")105 unmodified lines# Get validated API keyapi_key = st.session_state.get('validated_api_key', '')# Call API with file link and configurationresult = call_generation_api(file_link, config, api_key)# Handle API responseif result.get("success", False):386 unmodified lines3873883893903913923931 unmodified line3953963973983994004011 unmodified line4034044054064074084094104114124134144154164174184194204214223 unmodified lines4264274284294304314324334344354364374384394404414424434444454464474482 unmodified lines451452453454455456457458459460105 unmodified lines566567568569570571572573574575576577578579580581386 unmodified linesst.info("🎯 **Ready to generate!** Click the generate button above.")def call_generation_api(file_link, config, api_key, file_metadata=None):"""Call the generation API with file link and configuration1 unmodified linefile_link (str): AWS S3 link to the uploaded fileconfig (dict): All configuration settings including generation settingsapi_key (str): Validated API keyfile_metadata (dict): File metadata including size and row countReturns:dict: Generated data response1 unmodified line# Construct API URL and payloadapi_url = f"{API_BASE_URL}/{GENERATION_API_ENDPOINT}"payload = {"fileUrl": file_link,"type": "tabular","numberOfRows": config.get("num_rows", 100)}# Add file metadata if availableif 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 specifiedif config.get("target_column", "").strip():payload["targetColumn"] = config["target_column"].strip()# Prepare encrypted headerstry:3 unmodified lines# Make API calltry:# Print request details before sending to APIprint("="*50)print("📤 GENERATION API REQUEST")print("="*50)print(f"URL: {api_url}")print(f"Method: POST")print("Headers:")for key, value in headers.items():# Don't print the actual encrypted API key for securityif key.lower() == 'x-api-key':print(f" {key}: {'*' * 20}...{value[-4:] if len(value) > 4 else '****'}")else:print(f" {key}: {value}")print("Request Body (JSON):")print(json.dumps(payload, indent=2, default=str))print("="*50)st.info("🔄 Making API call...")response = requests.post(api_url, json=payload, headers=headers, timeout=API_TIMEOUT)2 unmodified linesresult = response.json()# Check if API returns an S3 URL for the generated fileif "fileUrl" in result or "s3Url" in result or "downloadUrl" in result or "file_url" in result or "s3_url" in result or "download_url" in result:# Extract the S3 URL from response (check camelCase first, then snake_case for backward compatibility)s3_url = (result.get("fileUrl") or result.get("s3Url") or result.get("downloadUrl") orresult.get("file_url") or result.get("s3_url") or result.get("download_url"))st.info("📥 Downloading generated file from S3...")105 unmodified lines# Get validated API keyapi_key = st.session_state.get('validated_api_key', '')# Get file metadata from session statefile_metadata = None# Look for file metadata in session statefor key in st.session_state.keys():if isinstance(key, str) and key.startswith('file_metadata_'):file_metadata = st.session_state[key]break# Call API with file link, configuration, and file metadataresult = call_generation_api(file_link, config, api_key, file_metadata)# Handle API responseif result.get("success", False):
54 unmodified lines5556575859606116 unmodified lines7879808182831 unmodified line85868788899054 unmodified lines# Determine allowed file types based on output formatoutput_format = st.session_state.get('output_format', 'tabular')# For now, only support tabular (CSV files)allowed_types = ['csv']help_text = "For tabular data generation: Upload CSV files only"upload_icon = "⬆️"16 unmodified linesif file_info["success"]:st.success("✅ File uploaded successfully!")# Display file metrics in a cleaner waycol_name, col_size = st.columns(2)with col_name:1 unmodified linewith col_size:st.metric("Size", f"{file_info['size_kb']:.1f} KB")# Display file previewif file_info["preview_type"] == "dataframe":st.markdown("**Preview:**")54 unmodified lines5556575859606116 unmodified lines78798081828384858687888990911 unmodified line9394959697989910010110210310410510654 unmodified lines# Determine allowed file types based on output formatoutput_format = st.session_state.get('output_format', 'tabular')# For now, only support tabular (CSV files only)allowed_types = ['csv']help_text = "For tabular data generation: Upload CSV files only"upload_icon = "⬆️"16 unmodified linesif file_info["success"]:st.success("✅ File uploaded successfully!")# Store file metadata in session state for API usagefile_metadata_key = f"file_metadata_{uploaded_file.name}_{uploaded_file.size}"st.session_state[file_metadata_key] = {"file_size_bytes": file_info.get("size_bytes", len(uploaded_file.getvalue())),"num_rows": file_info.get("num_rows", 0),"filename": file_info["name"]}# Display file metrics in a cleaner waycol_name, col_size = st.columns(2)with col_name:1 unmodified linewith col_size:st.metric("Size", f"{file_info['size_kb']:.1f} KB")# Show row count if availableif "num_rows" in file_info:col_rows, col_space = st.columns(2)with col_rows:st.metric("Rows", f"{file_info['num_rows']:,}")with col_space:pass# Display file previewif file_info["preview_type"] == "dataframe":st.markdown("**Preview:**")
52 unmodified lines535455565758596061626377 unmodified lines14114214314414514614714814915052 unmodified linesstart_time = time.time()try:# Make the API call with encrypted keyresponse = requests.post(validation_url,headers=headers,json={"apiKey": encrypted_api_key},timeout=API_TIMEOUT)77 unmodified linesdf = pd.read_csv(uploaded_file)file_info["preview"] = df.head(3)file_info["preview_type"] = "dataframe"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 contentfile_info["preview_type"] = "text"return file_infoexcept Exception as e:52 unmodified lines53545556575859606162636465666768697071727374757677787977 unmodified lines15715815916016116216316416516616716816952 unmodified linesstart_time = time.time()try:# Print request details before sending to validation APIvalidation_payload = {"apiKey": encrypted_api_key}print("="*50)print("🔐 API KEY VALIDATION REQUEST")print("="*50)print(f"URL: {validation_url}")print(f"Method: POST")print("Headers:")for key, value in headers.items():print(f" {key}: {value}")print("Request Body (JSON):")# Don't print the actual encrypted API key for security - just show structuremasked_payload = {"apiKey": f"{'*' * 20}...{encrypted_api_key[-4:] if len(encrypted_api_key) > 4 else '****'}"}print(json.dumps(masked_payload, indent=2))print("="*50)# Make the API call with encrypted keyresponse = requests.post(validation_url,headers=headers,json=validation_payload,timeout=API_TIMEOUT)77 unmodified linesdf = 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 contentfile_info["preview_type"] = "text"file_info["size_bytes"] = len(uploaded_file.getvalue())return file_infoexcept Exception as e:
requirements.txt-1
src/components/data_generation.py+42-9
src/components/file_processing.py+17-1
src/utils/data_processing.py+20-1