🔍 Code Extractor

function smartstat_download_log

Maturity: 54

Flask API endpoint that generates and downloads an execution log file containing the analysis history and debug information for a SmartStat session.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
5456 - 5547
Complexity:
moderate

Purpose

This endpoint retrieves execution logs for a SmartStat analysis session, either from an active session in memory or by recovering it from persisted data section metadata. It formats the analysis history, including queries, timestamps, models used, iterations, and debug logs into a downloadable text file. This is useful for debugging, auditing, and reviewing the execution flow of statistical analyses.

Source Code

def smartstat_download_log(session_id):
    """Download the execution log from analysis"""
    from pathlib import Path
    from flask import send_file
    import tempfile
    import io
    
    try:
        user_email = get_current_user()
        
        # Get or recover session
        session = smartstat_service.get_session(session_id)
        if not session:
            # Try to recover from data section metadata
            all_sections = data_section_service.get_user_data_sections(user_email)
            data_section = next((ds for ds in all_sections if ds.analysis_session_id == session_id), None)
            
            if data_section and data_section.metadata and 'analysis_history' in data_section.metadata:
                # Generate log from metadata
                log_content = f"SmartStat Execution Log\n"
                log_content += f"Session ID: {session_id}\n"
                log_content += f"=" * 80 + "\n\n"
                
                for idx, analysis in enumerate(data_section.metadata['analysis_history'], 1):
                    log_content += f"Analysis #{idx}\n"
                    log_content += f"Query: {analysis.get('query', 'N/A')}\n"
                    log_content += f"Timestamp: {analysis.get('timestamp', 'N/A')}\n"
                    log_content += f"Model: {analysis.get('model', 'N/A')}\n"
                    log_content += f"Iterations: {analysis.get('iterations', 'N/A')}\n"
                    log_content += f"-" * 80 + "\n"
                    
                    if 'debug_log' in analysis and analysis['debug_log']:
                        log_content += "\nDebug Log:\n"
                        for debug_entry in analysis['debug_log']:
                            log_content += f"\nIteration {debug_entry.get('iteration', '?')}:\n"
                            log_content += f"Error: {debug_entry.get('error', 'N/A')}\n"
                            if 'fix_attempt' in debug_entry:
                                log_content += f"Fix Attempt: {debug_entry['fix_attempt']}\n"
                            log_content += "\n"
                    
                    log_content += "\n" + "=" * 80 + "\n\n"
                
                # Return as downloadable file
                return send_file(
                    io.BytesIO(log_content.encode('utf-8')),
                    as_attachment=True,
                    download_name=f'execution_{session_id}.log',
                    mimetype='text/plain'
                )
            else:
                return jsonify({'error': 'Session not found'}), 404
        
        # If session exists in memory, generate log from current history
        log_content = f"SmartStat Execution Log\n"
        log_content += f"Session ID: {session_id}\n"
        log_content += f"=" * 80 + "\n\n"
        
        if hasattr(session, 'analysis_history') and session.analysis_history:
            for idx, analysis in enumerate(session.analysis_history, 1):
                log_content += f"Analysis #{idx}\n"
                log_content += f"Query: {analysis.get('query', 'N/A')}\n"
                log_content += f"Timestamp: {analysis.get('timestamp', 'N/A')}\n"
                log_content += f"Model: {analysis.get('model', 'N/A')}\n"
                log_content += f"Iterations: {analysis.get('iterations', 'N/A')}\n"
                log_content += f"-" * 80 + "\n"
                
                if 'debug_log' in analysis and analysis['debug_log']:
                    log_content += "\nDebug Log:\n"
                    for debug_entry in analysis['debug_log']:
                        log_content += f"\nIteration {debug_entry.get('iteration', '?')}:\n"
                        log_content += f"Error: {debug_entry.get('error', 'N/A')}\n"
                        if 'fix_attempt' in debug_entry:
                            log_content += f"Fix Attempt: {debug_entry['fix_attempt']}\n"
                        log_content += "\n"
                
                log_content += "\n" + "=" * 80 + "\n\n"
        else:
            log_content += "No analysis history available.\n"
        
        # Return as downloadable file
        return send_file(
            io.BytesIO(log_content.encode('utf-8')),
            as_attachment=True,
            download_name=f'execution_{session_id}.log',
            mimetype='text/plain'
        )
        
    except Exception as e:
        logger.error(f"Error generating execution log: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
session_id - - positional_or_keyword

Parameter Details

session_id: String identifier for the SmartStat analysis session. Used to locate the session either in active memory or in persisted data sections. Must be a valid session ID that was previously created during a SmartStat analysis.

Return Value

Returns a Flask response object containing either: (1) A downloadable text file (mimetype='text/plain') with the formatted execution log named 'execution_{session_id}.log', or (2) A JSON error response with status code 404 if session not found, or (3) A JSON error response with status code 500 if an exception occurs during log generation.

Dependencies

  • flask
  • pathlib
  • tempfile
  • io
  • json
  • logging
  • traceback

Required Imports

from flask import send_file, jsonify
from pathlib import Path
import tempfile
import io
import traceback

Conditional/Optional Imports

These imports are only needed under specific conditions:

from pathlib import Path

Condition: imported inside function but always used

Required (conditional)
from flask import send_file

Condition: imported inside function but always used for file download

Required (conditional)
import tempfile

Condition: imported inside function but not actively used in current implementation

Optional
import io

Condition: imported inside function and used for BytesIO operations

Required (conditional)

Usage Example

# Client-side usage (JavaScript fetch example)
fetch('/api/smartstat/abc123-session-id/download-log', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer <auth_token>'
  }
})
.then(response => response.blob())
.then(blob => {
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'execution_abc123-session-id.log';
  a.click();
})
.catch(error => console.error('Error downloading log:', error));

# Server-side route registration (already decorated)
# The function is automatically registered as a Flask route
# GET /api/smartstat/<session_id>/download-log

Best Practices

  • Always ensure the session_id parameter is validated and sanitized before use
  • The function implements a fallback mechanism: first checks active sessions, then attempts recovery from persisted metadata
  • Error handling is comprehensive with try-catch blocks and detailed logging
  • The log file is generated in-memory using BytesIO to avoid filesystem operations
  • Authentication is enforced via the require_auth decorator
  • The function handles missing or incomplete analysis history gracefully
  • Debug logs are optional and only included if present in the analysis history
  • Consider implementing rate limiting for this endpoint to prevent abuse
  • The log format is human-readable with clear section separators
  • UTF-8 encoding is used to ensure proper character handling in log content
  • Traceback is printed to console for debugging but not exposed to client
  • The download_name parameter ensures consistent file naming convention

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function smartstat_download_script 81.8% similar

    Flask route handler that downloads a generated Python analysis script for a specific SmartStat session by locating the most recent project directory and returning the analysis.py file.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function smartstat_get_history 75.8% similar

    Flask API endpoint that retrieves analysis history for a SmartStat session, with automatic session recovery from saved data if the session is not found in memory.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function smartstat_run_analysis 71.3% similar

    Flask API endpoint that initiates a SmartStat statistical analysis in a background thread, tracking progress and persisting results to a data section.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function smartstat_save_to_document 71.0% similar

    Flask route handler that saves SmartStat statistical analysis results back to a data section document, generating a final report with queries, results, and plots.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function smartstat_upload_data 69.8% similar

    Flask route handler that uploads CSV or Excel data files to a SmartStat analysis session, with support for multi-sheet Excel files and session recovery.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
← Back to Browse