kan0621 commited on
Commit
fe4bee3
·
verified ·
1 Parent(s): 6b699cc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -33
app.py CHANGED
@@ -469,16 +469,24 @@ def generate_stimulus(session_id):
469
  }
470
  df, filename = generate_stimuli(settings)
471
 
472
- # Check if there is a stop signal again
473
- if session_state['stop_event'].is_set():
 
474
  print(
475
  f"Session {session_id} - Stop detected after generation completed.")
476
- return
477
 
478
  # Verify the returned results
479
  print(settings["ablation"])
480
- if settings["ablation"]["use_agent_2"] == True:
481
- if df is None or filename is None:
 
 
 
 
 
 
 
482
  error_msg = "Generation process returned None for dataframe or filename"
483
  print(f"Session {session_id} - {error_msg}")
484
  session_state['error_message'] = error_msg
@@ -486,7 +494,8 @@ def generate_stimulus(session_id):
486
  websocket_send(session_id, 'error', error_msg)
487
  return
488
 
489
- # Verify the number of generated stimuli
 
490
  if len(df) != settings['iteration']:
491
  warning_msg = f"Warning: Expected {settings['iteration']} stimuli but got {len(df)}"
492
  print(f"Session {session_id} - {warning_msg}")
@@ -519,11 +528,19 @@ def generate_stimulus(session_id):
519
  # Use the newly generated file name
520
  session_state['generation_file'] = updated_filename
521
 
522
- # Record the successful completion
523
- print(
524
- f"Session {session_id} - Generation completed successfully. New file: {updated_filename}, Stimuli count: {len(df)}")
525
- websocket_send(
526
- session_id, 'all', f"Generation completed. Generated {len(df)} stimuli.")
 
 
 
 
 
 
 
 
527
 
528
  # Save the updated session state
529
  save_session(session_id, session_state)
@@ -587,15 +604,41 @@ def generation_status(session_id):
587
 
588
  # First check stop_event
589
  if session_state['stop_event'].is_set():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590
  print(
591
  f"Session {session_id} - Generation stopped by user (in-memory check).")
592
- # Send additional WebSocket notification
593
- websocket_send(session_id, 'all',
594
- "Generation stopped by user.")
595
- # Clear the generation file field, ensuring that the previous file is not returned
596
- session_state['generation_file'] = None
597
- save_session(session_id, session_state)
598
- return jsonify({'status': 'stopped'})
 
 
 
 
 
 
 
 
 
 
 
 
599
 
600
  if session_state['error_message']:
601
  return jsonify({'status': 'error', 'error_message': session_state['error_message']})
@@ -643,14 +686,23 @@ def generation_status(session_id):
643
 
644
  # First check stop_event
645
  if session_state['stop_event'].is_set():
646
- # If the stop signal is already set, ensure the frontend knows it has stopped
647
  print(f"Session {session_id} - Generation stopped by user.")
648
- # Send additional WebSocket notification
649
- websocket_send(session_id, 'all', "Generation stopped by user.")
650
- # Clear the generation file field, ensuring that the previous file is not returned
651
- session_state['generation_file'] = None
652
- save_session(session_id, session_state)
653
- return jsonify({'status': 'stopped'})
 
 
 
 
 
 
 
 
 
 
654
 
655
  if session_state['error_message']:
656
  return jsonify({'status': 'error', 'error_message': session_state['error_message']})
@@ -687,27 +739,30 @@ def stop_generation(session_id):
687
  session_state = active_sessions[session_id]
688
  # Directly set the stop_event in memory
689
  session_state['stop_event'].set()
690
- # Clear the previous file information, preventing the return of old files
691
- session_state['generation_file'] = None
692
  print(
693
- f"Session {session_id} - Stop signal set directly in memory. Generation will be stopped immediately.")
 
 
 
694
  # Still save to file for persistence
695
  save_session(session_id, session_state)
696
- return jsonify({'message': 'Stimulus generation successfully stopped.'})
697
 
698
  # If there is no active session in the global dictionary, fall back to loading from the file
699
  session_state = load_session(session_id)
700
  # Set the stop signal
701
  session_state['stop_event'].set()
702
- # Clear the previous file information, preventing the return of old files
703
- session_state['generation_file'] = None
704
  # Send the stop message through WebSocket
705
- websocket_send(session_id, 'all', "Stopping... Please wait.")
 
706
  print(
707
  f"Session {session_id} - Stop signal set. Generation will be stopped.")
708
  # Save the updated state
709
  save_session(session_id, session_state)
710
- return jsonify({'message': 'Stimulus generation successfully stopped.'})
711
 
712
 
713
  @app.route('/<session_id>/download/<filename>', methods=['GET'])
 
469
  }
470
  df, filename = generate_stimuli(settings)
471
 
472
+ # Check if there is a stop signal - but still save partial data if available
473
+ is_stopped = session_state['stop_event'].is_set()
474
+ if is_stopped:
475
  print(
476
  f"Session {session_id} - Stop detected after generation completed.")
477
+ # Don't return immediately - continue to save any partial data
478
 
479
  # Verify the returned results
480
  print(settings["ablation"])
481
+ if df is None or filename is None:
482
+ if is_stopped:
483
+ # Stopped before any data was generated
484
+ print(
485
+ f"Session {session_id} - Stopped with no data generated")
486
+ websocket_send(
487
+ session_id, 'all', "Generation stopped. No data was generated.")
488
+ return
489
+ else:
490
  error_msg = "Generation process returned None for dataframe or filename"
491
  print(f"Session {session_id} - {error_msg}")
492
  session_state['error_message'] = error_msg
 
494
  websocket_send(session_id, 'error', error_msg)
495
  return
496
 
497
+ # Verify the number of generated stimuli
498
+ if not is_stopped and settings["ablation"]["use_agent_2"] == True:
499
  if len(df) != settings['iteration']:
500
  warning_msg = f"Warning: Expected {settings['iteration']} stimuli but got {len(df)}"
501
  print(f"Session {session_id} - {warning_msg}")
 
528
  # Use the newly generated file name
529
  session_state['generation_file'] = updated_filename
530
 
531
+ # Record the completion status
532
+ if is_stopped:
533
+ print(
534
+ f"Session {session_id} - Generation stopped with partial data. File: {updated_filename}, Stimuli count: {len(df)}")
535
+ websocket_send(
536
+ session_id, 'all', f"Generation stopped. Saved {len(df)} stimuli.")
537
+ # Don't clear stop_event here - let status check handle it
538
+ # so it can detect this is a stopped generation with partial data
539
+ else:
540
+ print(
541
+ f"Session {session_id} - Generation completed successfully. New file: {updated_filename}, Stimuli count: {len(df)}")
542
+ websocket_send(
543
+ session_id, 'all', f"Generation completed. Generated {len(df)} stimuli.")
544
 
545
  # Save the updated session state
546
  save_session(session_id, session_state)
 
604
 
605
  # First check stop_event
606
  if session_state['stop_event'].is_set():
607
+ # Check if the generation thread is still running
608
+ thread_running = session_state['generation_thread'] and session_state['generation_thread'].is_alive(
609
+ )
610
+
611
+ if thread_running:
612
+ # Thread is still running, wait for it to save partial data
613
+ print(
614
+ f"Session {session_id} - Stop signal set, waiting for thread to save partial data...")
615
+ # Return running status so frontend keeps polling
616
+ progress = (session_state['current_iteration'].value /
617
+ session_state['total_iterations'].value) * 100
618
+ progress = min(100, max(0, progress))
619
+ return jsonify({'status': 'running', 'progress': progress, 'stopping': True})
620
+
621
  print(
622
  f"Session {session_id} - Generation stopped by user (in-memory check).")
623
+ # Thread has finished - check if there's partial data available for download
624
+ if session_state['generation_file'] and session_state['dataframe'] is not None:
625
+ filename = session_state['generation_file']
626
+ row_count = len(session_state['dataframe'])
627
+ print(
628
+ f"Session {session_id} - Returning partial data file: {filename} with {row_count} rows")
629
+ websocket_send(session_id, 'all',
630
+ f"Generation stopped. {row_count} stimuli saved.")
631
+ # Clear stop event so we don't keep returning stopped status
632
+ session_state['stop_event'].clear()
633
+ save_session(session_id, session_state)
634
+ return jsonify({'status': 'completed', 'file': filename, 'partial': True})
635
+ else:
636
+ # No data to save
637
+ websocket_send(session_id, 'all',
638
+ "Generation stopped by user.")
639
+ session_state['generation_file'] = None
640
+ save_session(session_id, session_state)
641
+ return jsonify({'status': 'stopped'})
642
 
643
  if session_state['error_message']:
644
  return jsonify({'status': 'error', 'error_message': session_state['error_message']})
 
686
 
687
  # First check stop_event
688
  if session_state['stop_event'].is_set():
 
689
  print(f"Session {session_id} - Generation stopped by user.")
690
+ # Check if there's partial data available for download
691
+ if session_state['generation_file'] and session_state.get('dataframe') is not None:
692
+ filename = session_state['generation_file']
693
+ row_count = len(session_state['dataframe'])
694
+ print(
695
+ f"Session {session_id} - Returning partial data file (from disk): {filename} with {row_count} rows")
696
+ websocket_send(session_id, 'all',
697
+ f"Generation stopped. {row_count} stimuli saved.")
698
+ session_state['stop_event'].clear()
699
+ save_session(session_id, session_state)
700
+ return jsonify({'status': 'completed', 'file': filename, 'partial': True})
701
+ else:
702
+ websocket_send(session_id, 'all', "Generation stopped by user.")
703
+ session_state['generation_file'] = None
704
+ save_session(session_id, session_state)
705
+ return jsonify({'status': 'stopped'})
706
 
707
  if session_state['error_message']:
708
  return jsonify({'status': 'error', 'error_message': session_state['error_message']})
 
739
  session_state = active_sessions[session_id]
740
  # Directly set the stop_event in memory
741
  session_state['stop_event'].set()
742
+ # Don't clear generation_file here - let the generation thread save partial data
743
+ # The status check will return the file if partial data is available
744
  print(
745
+ f"Session {session_id} - Stop signal set directly in memory. Generation will be stopped and partial data saved.")
746
+ # Send the stop message through WebSocket
747
+ websocket_send(
748
+ session_id, 'all', "Stopping... Please wait for partial data to be saved.")
749
  # Still save to file for persistence
750
  save_session(session_id, session_state)
751
+ return jsonify({'message': 'Stopping generation. Partial data will be saved if available.'})
752
 
753
  # If there is no active session in the global dictionary, fall back to loading from the file
754
  session_state = load_session(session_id)
755
  # Set the stop signal
756
  session_state['stop_event'].set()
757
+ # Don't clear generation_file - let the generation thread save partial data
 
758
  # Send the stop message through WebSocket
759
+ websocket_send(session_id, 'all',
760
+ "Stopping... Please wait for partial data to be saved.")
761
  print(
762
  f"Session {session_id} - Stop signal set. Generation will be stopped.")
763
  # Save the updated state
764
  save_session(session_id, session_state)
765
+ return jsonify({'message': 'Stopping generation. Partial data will be saved if available.'})
766
 
767
 
768
  @app.route('/<session_id>/download/<filename>', methods=['GET'])