File size: 21,232 Bytes
61e7b06
 
 
 
 
 
 
8c9119d
61e7b06
 
 
8c9119d
b625fd8
8c9119d
b625fd8
 
 
 
 
 
 
0726658
 
 
d428254
 
b625fd8
 
 
 
d428254
b625fd8
8c9119d
 
 
 
b625fd8
 
 
 
4c2379f
8c9119d
 
 
 
 
 
 
 
 
 
 
 
b625fd8
 
 
 
 
 
 
 
74f3fe5
4c2379f
 
52de8f8
b625fd8
 
61e7b06
 
 
 
b625fd8
 
 
8c9119d
61e7b06
 
 
 
 
 
 
 
 
74f3fe5
 
 
 
 
 
 
 
61e7b06
 
 
 
 
 
 
74f3fe5
 
 
 
 
 
 
 
61e7b06
 
 
 
 
 
 
b625fd8
8c9119d
b625fd8
8c9119d
b625fd8
 
8c9119d
b625fd8
 
 
8c9119d
 
 
 
 
b625fd8
 
8c9119d
b625fd8
 
 
 
 
8c9119d
 
 
 
 
 
b625fd8
8c9119d
 
 
 
 
 
 
 
 
 
b625fd8
8c9119d
 
b625fd8
8c9119d
 
e1b7040
 
8c9119d
e1b7040
 
 
 
8c9119d
 
 
 
 
61e7b06
 
b625fd8
 
4c2379f
8c9119d
 
 
 
 
 
 
 
 
 
 
b625fd8
 
61e7b06
 
b625fd8
 
 
 
8c9119d
b625fd8
 
 
 
 
 
8c9119d
 
 
 
 
b625fd8
 
4c2379f
 
8c9119d
 
b625fd8
 
8c9119d
b625fd8
8c9119d
b625fd8
 
 
 
 
 
8c9119d
b625fd8
 
8c9119d
b625fd8
8c9119d
b625fd8
 
8c9119d
 
b625fd8
 
 
 
8c9119d
b625fd8
 
 
8c9119d
b625fd8
 
 
8c9119d
 
 
 
 
b625fd8
 
8c9119d
b625fd8
 
 
 
 
 
8c9119d
 
 
 
 
 
 
 
 
 
 
 
b625fd8
8c9119d
 
b625fd8
8c9119d
 
e1b7040
 
8c9119d
e1b7040
 
 
 
8c9119d
 
 
 
 
b625fd8
8c9119d
b625fd8
 
 
 
61e7b06
b625fd8
 
 
 
61e7b06
b625fd8
8c9119d
b625fd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d428254
 
 
 
 
 
 
 
 
b625fd8
 
 
 
d428254
b625fd8
 
 
4c2379f
 
 
b625fd8
 
 
 
 
4c2379f
 
b625fd8
4c2379f
 
b625fd8
 
4c2379f
b625fd8
4c2379f
61e7b06
 
4c2379f
 
 
 
 
61e7b06
 
52de8f8
 
4c2379f
 
 
 
52de8f8
 
 
 
4c2379f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61e7b06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
"""
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")