tabular-generation-test / src /components /file_processing.py
Khushal-kreeda
fix: minor fix
0726658
Raw History Blame Contribute Delete
21.2 kB
"""
File upload and processing components
"""
import streamlit as st
import time
from utils.data_processing import process_uploaded_file
from utils.aws_s3 import upload_file_to_s3, check_aws_credentials
from config.settings import SUPPORTED_FILE_TYPES, UPLOAD_HELP_TEXT
def render_file_upload_with_cloud_section(enabled=True):
"""
Render file upload section that automatically uploads to cloud storage and returns file link
Args:
enabled: Whether this step is enabled
Returns:
tuple: (uploaded_file, file_link)
"""
# Use the enabled parameter passed from main function
# This ensures consistent state across the application
is_enabled = enabled
if is_enabled:
st.markdown('<h3 class="section-title step-incomplete">πŸ“ Step 2: Upload Files</h3>', unsafe_allow_html=True)
else:
st.markdown('<h3 class="section-title step-disabled">πŸ“ Step 2: Upload Files πŸ”’</h3>', unsafe_allow_html=True)
if not is_enabled:
st.info("πŸ”’ Complete Step 1 (API Key Validation) to enable file upload")
# Disabled output format selection with styling
st.markdown('<div class="format-disabled">', unsafe_allow_html=True)
st.markdown("**Output Format**")
col_tab, col_json = st.columns(2)
with col_tab:
st.button("πŸ“Š Tabular", disabled=True, use_container_width=True)
with col_json:
st.button("πŸ“„ JSONL (Coming Soon)", disabled=True, use_container_width=True)
st.markdown('</div>', unsafe_allow_html=True)
# Improved disabled file upload area
st.markdown("**πŸ“ File Upload**")
st.markdown('''
<div class="upload-area-disabled">
<div class="upload-icon" style="font-size: 3rem; margin-bottom: 1rem;">πŸ“„</div>
<div class="upload-text" style="font-size: 1.1rem; margin-bottom: 0.5rem;">File upload disabled</div>
<div style="font-size: 0.9rem; color: #6b7280;">Complete API key validation to enable file upload</div>
<div style="font-size: 0.8rem; color: #4a5568; margin-top: 1rem;">Supported formats: CSV files</div>
</div>
''', unsafe_allow_html=True)
return None, None
# Show output format selection first
render_output_format_selection()
# Determine allowed file types based on output format
output_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 = "⬆️"
st.markdown(f"**{upload_icon} Upload {output_format.upper()} Source File**")
# File upload
uploaded_file = st.file_uploader(
"Choose your data file",
type=allowed_types,
help=help_text,
label_visibility="collapsed",
key=f"main_file_upload_{output_format}" # Unique key to prevent duplication
)
if uploaded_file is not None:
# Process and display file info
file_info = process_uploaded_file(uploaded_file)
if file_info["success"]:
st.success("βœ… File uploaded successfully!")
# Store file metadata in session state for API usage
file_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 way
col_name, col_size = st.columns(2)
with col_name:
st.metric("Filename", file_info["name"])
with col_size:
st.metric("Size", f"{file_info['size_kb']:.1f} KB")
# Show row count if available
if "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 preview
if file_info["preview_type"] == "dataframe":
st.markdown("**Preview:**")
st.dataframe(file_info["preview"], use_container_width=True)
elif file_info["preview_type"] == "text":
st.markdown("**Preview:**")
st.text_area("", file_info["preview"], height=100, disabled=True, key="file_preview")
# Automatic Cloud Upload
st.markdown("---")
st.markdown("**☁️ Uploading to cloud storage...**")
# Check if we already have a file link for this file in session state
file_key = f"cloud_file_link_{uploaded_file.name}_{uploaded_file.size}"
if file_key in st.session_state:
file_link = st.session_state[file_key]
st.success(f"βœ… File already uploaded to cloud storage!")
# Show a clean display URL without exposing bucket details
display_url = f"πŸ—‚οΈ File stored securely in cloud storage"
st.info(display_url)
# Option to re-upload
if st.button("πŸ”„ Re-upload to Cloud"):
del st.session_state[file_key]
st.rerun()
return uploaded_file, file_link
else:
# Check cloud storage credentials first
aws_status = check_aws_credentials()
if not aws_status['valid']:
st.error(f"❌ Cloud Storage Configuration Error: {aws_status['message']}")
st.info("πŸ’‘ **To enable cloud upload:**\n1. Copy `.env.example` to `.env`\n2. Add your storage credentials\n3. Restart the application")
# Provide fallback mock URL for development
st.warning("⚠️ **Development Mode**: Using mock file URL")
file_link = f"mock://local-dev/{uploaded_file.name}"
st.session_state[file_key] = file_link
return uploaded_file, file_link
# Auto-upload to cloud storage
with st.spinner("Uploading file to cloud storage..."):
# Reset file pointer before upload
uploaded_file.seek(0)
# Upload to cloud storage
upload_result = upload_file_to_s3(uploaded_file)
if upload_result['success']:
file_link = upload_result['url']
# Store both URLs for fallback
st.session_state[file_key] = file_link
st.session_state['current_file_key'] = file_key # Track current file key
if upload_result.get('presigned_url'):
st.session_state[f"{file_key}_presigned"] = upload_result['presigned_url']
st.session_state[f"cloud_storage_key_{file_key}"] = upload_result['key'] # Store key for deletion
st.rerun()
else:
st.error(f"❌ Upload failed: {upload_result['error']}")
return uploaded_file, None
else:
st.error(f"❌ {file_info['error']}")
return uploaded_file, None
else:
# Format-specific empty state - only CSV supported now
if output_format == "tabular":
st.markdown('''
<div class="upload-area">
<div style="font-size: 3rem; margin-bottom: 1rem;">πŸ“Š</div>
<div style="font-size: 1.2rem; font-weight: 600; margin-bottom: 0.5rem; color: #e5e5e5;">Drop your CSV file here</div>
<div style="font-size: 0.9rem; color: #9ca3af; margin-bottom: 1rem;">or click to browse</div>
<div style="font-size: 0.8rem; color: #6b7280;">Supported: CSV files only</div>
</div>
''', unsafe_allow_html=True)
else:
st.info("πŸ“„ **JSONL format coming soon**\n\nPlease select Tabular format for now")
return uploaded_file, None
def render_output_format_selection():
"""Render output format selection"""
st.markdown("**Output Format**")
current_format = st.session_state.get('output_format', 'tabular')
# Create two columns for the buttons
col_tab, col_json = st.columns(2)
with col_tab:
if st.button("πŸ“Š Tabular", use_container_width=True,
type="primary" if current_format == "tabular" else "secondary",
key="format_tabular_btn"):
if current_format != "tabular":
st.session_state.output_format = "tabular"
st.rerun()
with col_json:
# Disable JSONL for now
st.button("πŸ“„ JSONL (Coming Soon)", use_container_width=True,
disabled=True, help="JSONL format will be available in a future update",
key="format_jsonl_btn")
def render_cloud_upload_section(uploaded_file, enabled=True):
"""
Handle cloud storage upload and return file link
Args:
uploaded_file: Streamlit uploaded file object
enabled: Whether this step is enabled
Returns:
str: Cloud file URL if successful, None otherwise
"""
if enabled:
st.markdown('<h3 class="section-title step-incomplete">☁️ Step 3: Cloud Upload</h3>', unsafe_allow_html=True)
else:
st.markdown('<h3 class="section-title step-disabled">☁️ Step 3: Cloud Upload πŸ”’</h3>', unsafe_allow_html=True)
if not enabled:
st.info("πŸ”’ Complete Steps 1-2 (API Key + File Upload) to enable cloud upload")
st.button("☁️ Upload to Cloud Storage", disabled=True, use_container_width=True)
return None
if uploaded_file is None:
st.info("πŸ“ Please upload a file first")
st.button("☁️ Upload to Cloud Storage", disabled=True, use_container_width=True)
return None
# Check if we already have a file link for this file in session state
file_key = f"cloud_file_link_{uploaded_file.name}_{uploaded_file.size}"
if file_key in st.session_state:
file_link = st.session_state[file_key]
st.success(f"βœ… File already uploaded to cloud storage!")
# Show a clean display without exposing bucket details
display_url = f"πŸ—‚οΈ File stored securely in cloud storage"
st.info(display_url)
# Option to re-upload
if st.button("πŸ”„ Re-upload to Cloud"):
del st.session_state[file_key]
st.rerun()
return file_link
# Upload button
if st.button("☁️ Upload to Cloud Storage", use_container_width=True, type="primary"):
# Check cloud storage credentials first
aws_status = check_aws_credentials()
if not aws_status['valid']:
st.error(f"❌ Cloud Storage Configuration Error: {aws_status['message']}")
st.info("πŸ’‘ **To enable cloud upload:**\n1. Copy `.env.example` to `.env`\n2. Add your storage credentials\n3. Restart the application")
return None
with st.spinner("Uploading file to cloud storage..."):
# Reset file pointer before upload
uploaded_file.seek(0)
# Upload to cloud storage
upload_result = upload_file_to_s3(uploaded_file)
if upload_result['success']:
file_link = upload_result['url']
# Store both URLs for fallback
st.session_state[file_key] = file_link
st.session_state['current_file_key'] = file_key # Track current file key
if upload_result.get('presigned_url'):
st.session_state[f"{file_key}_presigned"] = upload_result['presigned_url']
st.session_state[f"cloud_storage_key_{file_key}"] = upload_result['key'] # Store key for deletion
st.rerun()
else:
st.error(f"❌ Upload failed: {upload_result['error']}")
return None
st.info("☁️ Click the button above to upload your file to cloud storage")
return None
def render_processing_config(enabled=True):
"""Render processing configuration section"""
if enabled:
st.markdown('<h3 class="section-title step-incomplete">βš™οΈ Step 4: Configuration</h3>', unsafe_allow_html=True)
else:
st.markdown('<h3 class="section-title step-disabled">βš™οΈ Step 4: Configuration πŸ”’</h3>', unsafe_allow_html=True)
if not enabled:
st.info("πŸ”’ Complete Steps 1-3 (API Key + File Upload + Cloud Upload) to enable configuration")
# Show disabled configuration UI
st.markdown("**Data Generation Settings**")
st.slider("Number of Records", min_value=10, max_value=1000, value=100, disabled=True)
st.checkbox("Maintain Data Relationships", value=True, disabled=True)
st.checkbox("Include Null Values", value=False, disabled=True)
return None
# Get output format for conditional configuration
output_format = st.session_state.get('output_format', 'tabular')
if output_format == "tabular":
# Configuration for tabular data generation
st.markdown("**Data Generation Settings**")
num_records = st.slider(
"Number of Records",
min_value=10,
max_value=1000,
value=100,
step=10,
help="Number of synthetic records to generate"
)
maintain_relationships = st.checkbox(
"Maintain Data Relationships",
value=True,
help="Preserve relationships between columns in the original data"
)
include_nulls = st.checkbox(
"Include Null Values",
value=False,
help="Generate some null values to match real-world data patterns"
)
return {
"num_records": num_records,
"maintain_relationships": maintain_relationships,
"include_nulls": include_nulls,
"output_format": "tabular"
}
else: # jsonl
# Configuration for JSONL data generation from text
st.markdown("**Text Processing Settings**")
chunk_size = st.slider(
"Chunk Size (tokens)",
min_value=100,
max_value=2000,
value=800,
step=100,
help="Size of text chunks for processing"
)
chunk_overlap = st.slider(
"Chunk Overlap (tokens)",
min_value=0,
max_value=400,
value=150,
step=50,
help="Overlap between consecutive chunks"
)
min_chunk_chars = st.slider(
"Minimum Chunk Characters",
min_value=100,
max_value=1500,
value=400,
step=100,
help="Minimum characters required per chunk"
)
return {
"chunk_size": chunk_size,
"chunk_overlap": chunk_overlap,
"min_chunk_chars": min_chunk_chars,
"output_format": "jsonl"
}
def render_all_configuration(enabled=True):
"""Render all configuration settings in one step"""
# Double-check the validation and file upload state for consistency
actual_api_valid = (st.session_state.get('api_validation', {}).get('valid', False) and
st.session_state.get('validated_api_key', ''))
file_uploaded = any(str(key).startswith('cloud_file_link_') for key in st.session_state.keys())
# Use the most restrictive condition
is_enabled = enabled and actual_api_valid and file_uploaded
if is_enabled:
st.markdown('<h3 class="section-title step-incomplete">βš™οΈ Step 3: Configuration</h3>', unsafe_allow_html=True)
else:
st.markdown('<h3 class="section-title step-disabled">βš™οΈ Step 3: Configuration πŸ”’</h3>', unsafe_allow_html=True)
if not is_enabled:
st.info("πŸ”’ Complete Steps 1-2 (API Key + File Upload) to enable configuration")
# Show disabled configuration UI
st.markdown("**Tabular Generation Settings**")
st.slider("Number of Rows", min_value=10, max_value=1000, value=100, disabled=True)
st.text_input("Target Column", value="", disabled=True, placeholder="Enter target column name")
return None
# Get output format for conditional configuration
output_format = st.session_state.get('output_format', 'tabular')
# Configuration for tabular data generation only
st.markdown("**πŸ“Š Tabular Generation Settings**")
num_rows = st.slider(
"Number of Rows",
min_value=1,
max_value=1000,
value=100,
step=1,
help="Number of synthetic rows to generate"
)
target_column = st.text_input(
"Target Column",
value="",
placeholder="Enter the name of the target column",
help="Specify the target column name for prediction or classification tasks"
)
# Store configuration in session state for persistence
config = {
"num_rows": num_rows,
"target_column": target_column,
"output_format": "tabular"
}
st.session_state.config = config
return config
# TODO: Future JSONL Configuration (currently disabled)
# When JSONL is enabled, uncomment and integrate the following configuration:
#
# else: # jsonl
# # Configuration for JSONL data generation from text
# st.markdown("**πŸ“„ JSONL Generation Settings**")
#
# tone = st.selectbox(
# "Tone",
# options=["Professional", "Casual", "Academic", "Creative", "Technical"],
# index=0,
# help="Tone style for generated content"
# )
#
# depth = st.slider(
# "Depth",
# min_value=1,
# max_value=10,
# value=5,
# step=1,
# help="Depth of content generation (1=shallow, 10=deep)"
# )
#
# datapoints = st.slider(
# "Data Points",
# min_value=10,
# max_value=1000,
# value=100,
# step=10,
# help="Number of JSONL data points to generate"
# )
#
# return {
# "tone": tone,
# "depth": depth,
# "datapoints": datapoints,
# "output_format": "jsonl"
# }
def render_process_button(uploaded_file):
"""Render process files button and handle processing"""
process_clicked = st.button("πŸš€ Process Files", use_container_width=True)
if process_clicked:
if uploaded_file is not None:
with st.spinner("Processing file..."):
progress_bar = st.progress(0)
for i in range(100):
progress_bar.progress(i + 1)
time.sleep(0.02)
st.success("βœ… File processed successfully!")
return True
else:
st.error("❌ Please upload a file first")
return False
return False
def render_chunk_display(uploaded_file, is_processed=False):
"""Render document chunks display"""
st.markdown('<h3 class="section-title">πŸ“„ Document Chunks</h3>', unsafe_allow_html=True)
if uploaded_file is not None and is_processed:
st.success("βœ… Document chunks created")
# Mock chunk metrics
col_chunks, col_tokens = st.columns(2)
with col_chunks:
st.metric("Chunks", "12", "3")
with col_tokens:
st.metric("Total Tokens", "9,840", "2,100")
# Sample chunk preview
st.markdown("**Current Chunk:**")
st.text_area(
"",
"This is a sample chunk of the processed document containing relevant information for question-answer generation...",
height=120,
disabled=True,
key="chunk_preview"
)
# Navigation buttons
col_prev, col_next = st.columns(2)
with col_prev:
st.button("⬅️ Previous", use_container_width=True)
with col_next:
st.button("➑️ Next", use_container_width=True)
else:
st.info("πŸ“‹ Upload and process a file to see chunks")