🔍 Code Extractor

function smartstat_get_plot

Maturity: 48

Flask route handler that serves plot image files (PNG, JPG, SVG) generated by SmartStat analysis sessions from project directories.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
5401 - 5420
Complexity:
moderate

Purpose

This endpoint retrieves and serves statistical plot images created during SmartStat analysis sessions. It searches through project directories within a session folder to locate the requested plot file and returns it with the appropriate MIME type. The function is protected by authentication and handles file validation to ensure only image files are served.

Source Code

def smartstat_get_plot(session_id, filename):
    """Serve plot files from SmartStat analysis"""
    from pathlib import Path
    from flask import send_file
    
    try:
        # Find the plot file in project directories
        base_path = Path(smartstat_config.GENERATED_SCRIPTS_FOLDER) / session_id
        
        # Search all project directories
        for project_dir in base_path.glob('project_*'):
            plot_path = project_dir / filename
            if plot_path.exists() and plot_path.suffix in ['.png', '.jpg', '.svg']:
                return send_file(str(plot_path), mimetype=f'image/{plot_path.suffix[1:]}')
        
        return jsonify({'error': 'Plot not found'}), 404
        
    except Exception as e:
        logger.error(f"Error serving plot: {e}")
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
session_id - - positional_or_keyword
filename - - positional_or_keyword

Parameter Details

session_id: Unique identifier for the SmartStat analysis session. Used to locate the base directory containing project folders with generated plots. Expected to be a string (typically UUID format).

filename: Name of the plot file to retrieve, including extension. Must be a valid filename with one of the supported image extensions (.png, .jpg, .svg). The path: prefix in the route allows for nested paths within the filename.

Return Value

Returns a Flask Response object. On success: sends the image file with appropriate MIME type (image/png, image/jpg, or image/svg). On failure: returns a JSON object with an 'error' key and HTTP status code 404 (file not found) or 500 (server error). Response types: send_file() for success, jsonify() with error status for failures.

Dependencies

  • flask
  • pathlib

Required Imports

from pathlib import Path
from flask import send_file
from flask import jsonify

Conditional/Optional Imports

These imports are only needed under specific conditions:

from pathlib import Path

Condition: imported inside function for file path operations

Required (conditional)
from flask import send_file

Condition: imported inside function for serving files

Required (conditional)

Usage Example

# Example API call to retrieve a plot
import requests

# Assuming the Flask app is running on localhost:5000
session_id = 'abc123-session-uuid'
filename = 'correlation_plot.png'

# Make authenticated GET request
response = requests.get(
    f'http://localhost:5000/api/smartstat/plots/{session_id}/{filename}',
    headers={'Authorization': 'Bearer YOUR_AUTH_TOKEN'}
)

if response.status_code == 200:
    # Save the plot image
    with open('downloaded_plot.png', 'wb') as f:
        f.write(response.content)
    print('Plot downloaded successfully')
else:
    print(f'Error: {response.json()}')

# Example with nested path
filename_nested = 'subfolder/histogram.svg'
response = requests.get(
    f'http://localhost:5000/api/smartstat/plots/{session_id}/{filename_nested}',
    headers={'Authorization': 'Bearer YOUR_AUTH_TOKEN'}
)

Best Practices

  • The function validates file extensions to only serve image files (.png, .jpg, .svg), preventing unauthorized file access
  • Uses Path.glob() to search through multiple project directories, making it flexible for different project structures
  • Implements proper error handling with try-except blocks and returns appropriate HTTP status codes
  • Logs errors for debugging and monitoring purposes
  • Protected by require_auth decorator to ensure only authenticated users can access plots
  • Consider adding additional security checks for path traversal attacks if filename can contain directory separators
  • The function searches all project_* directories which could be slow with many projects - consider caching or indexing for performance
  • MIME type is dynamically determined from file extension, ensuring correct content-type headers
  • Returns 404 for missing files rather than exposing directory structure information

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function serve_plot 82.8% similar

    Flask route handler that serves generated plot image files from a session-specific plots directory.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function serve_analysis_plot 81.6% similar

    Flask route handler that serves analysis plot image files from the data analysis service's plots directory, with authentication and error handling.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function smartstat_save_selective 71.7% similar

    Flask route handler that saves selected statistical analysis rounds and their associated plots from a SmartStat session to a data section, with options to replace or append to existing content.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function smartstat_download_script 70.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_save_to_document 69.3% 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
← Back to Browse