🔍 Code Extractor

function get_statistical_interpretation_templates

Maturity: 51

Flask API endpoint that retrieves available statistical interpretation templates from a JSON file or returns default templates if the file doesn't exist.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
5210 - 5241
Complexity:
simple

Purpose

This endpoint provides a list of statistical interpretation templates that users can select from when generating statistical analysis reports. It reads template metadata (id, name, description) from a JSON configuration file, making it easy to manage and extend available templates without code changes. If the configuration file is missing, it falls back to two default templates (Standard Statistical Report and Executive Brief).

Source Code

def get_statistical_interpretation_templates():
    """Get available statistical interpretation templates"""
    try:
        from pathlib import Path
        templates_file = Path(__file__).parent / "statistical_interpretation_templates.json"
        
        if templates_file.exists():
            with open(templates_file, 'r') as f:
                templates = json.load(f)
            
            # Return just the template names and descriptions for selection
            template_list = []
            for key, template in templates.items():
                template_list.append({
                    'id': key,
                    'name': template['name'],
                    'description': template['description']
                })
            
            return jsonify({'templates': template_list})
        else:
            # Default templates if file doesn't exist
            return jsonify({
                'templates': [
                    {'id': 'standard', 'name': 'Standard Statistical Report', 'description': 'Comprehensive analysis report'},
                    {'id': 'brief', 'name': 'Executive Brief', 'description': 'Concise summary for decision-making'}
                ]
            })
    
    except Exception as e:
        logger.error(f"Error loading interpretation templates: {e}")
        return jsonify({'error': 'Failed to load templates'}), 500

Return Value

Returns a JSON response with status code 200 containing a 'templates' array of objects, where each object has 'id' (string identifier), 'name' (display name), and 'description' (template purpose). On error, returns a JSON object with an 'error' key and status code 500.

Dependencies

  • flask
  • json
  • pathlib
  • logging

Required Imports

from flask import jsonify
import json
from pathlib import Path

Conditional/Optional Imports

These imports are only needed under specific conditions:

from pathlib import Path

Condition: imported inside the function to locate the templates file relative to the current module

Required (conditional)

Usage Example

# As a Flask route endpoint:
# GET /api/smartstat/interpretation-templates
# Response example:
# {
#   "templates": [
#     {
#       "id": "standard",
#       "name": "Standard Statistical Report",
#       "description": "Comprehensive analysis report"
#     },
#     {
#       "id": "brief",
#       "name": "Executive Brief",
#       "description": "Concise summary for decision-making"
#     }
#   ]
# }

# Client-side usage:
import requests

response = requests.get(
    'http://your-app.com/api/smartstat/interpretation-templates',
    headers={'Authorization': 'Bearer YOUR_TOKEN'}
)

if response.status_code == 200:
    templates = response.json()['templates']
    for template in templates:
        print(f"{template['id']}: {template['name']} - {template['description']}")
else:
    print(f"Error: {response.json().get('error')}")

Best Practices

  • The function gracefully handles missing template files by providing sensible defaults
  • Error handling is implemented with try-except to catch file reading or JSON parsing errors
  • The function only returns template metadata (id, name, description), not full template content, keeping responses lightweight
  • Authentication is required via the require_auth decorator to protect template access
  • Errors are logged using the logger for debugging and monitoring
  • The templates file path is resolved relative to the module location using Path(__file__).parent for portability
  • Consider validating the JSON structure of the templates file to ensure required keys exist
  • The templates JSON file should be version-controlled separately from code for easier template management
  • Consider caching the templates in memory to avoid repeated file I/O on each request
  • HTTP status codes follow REST conventions (200 for success, 500 for server errors)

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_statistical_interpretation_template 88.7% similar

    Flask API endpoint that retrieves a specific statistical interpretation template by ID from a JSON file and returns its details including template content, name, and description.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_templates 64.0% similar

    Flask API endpoint that retrieves and returns a list of available instruction templates from the chat engine.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_templates_v2 63.7% similar

    Flask API endpoint that retrieves and returns a list of available instruction templates from the chat engine.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function get_instruction_templates 63.3% similar

    Flask API endpoint that returns a dictionary of predefined instruction templates for different document types including SOPs, work instructions, quality forms, and document comparison guidelines.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_templates_v1 61.9% similar

    Flask API endpoint that retrieves and returns a list of available instruction templates from the RAG engine.

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