""" Frontend Integration Example Demonstrates how to call the API from different frontend frameworks """ # ============================================================ # VANILLA JAVASCRIPT # ============================================================ vanilla_js = """ // Vanilla JavaScript Example // Get DOM elements const fileInput = document.getElementById('fileInput'); const predictButton = document.getElementById('predictButton'); const resultsDiv = document.getElementById('results'); // Add event listener predictButton.addEventListener('click', async () => { const file = fileInput.files[0]; if (!file) { alert('Please select an image first'); return; } // Create form data const formData = new FormData(); formData.append('file', file); // Show loading state resultsDiv.innerHTML = '

Analyzing image...

'; try { // Make API request const response = await fetch('http://localhost:8000/predict', { method: 'POST', body: formData }); const data = await response.json(); if (data.success) { // Display results const svm = data.predictions.svm; const cnn = data.predictions.cnn; const consensus = data.consensus; resultsDiv.innerHTML = `

Prediction Results

SVM Model

Prediction: ${svm.class}

Confidence: ${(svm.confidence * 100).toFixed(2)}%

Time: ${svm.inference_time_ms.toFixed(2)}ms

CNN Model (DenseNet121)

Prediction: ${cnn.class}

Confidence: ${(cnn.confidence * 100).toFixed(2)}%

Time: ${cnn.inference_time_ms.toFixed(2)}ms

Final Diagnosis

${consensus.predicted_class}

Models ${consensus.agreement ? 'agree' : 'disagree'}

`; } else { resultsDiv.innerHTML = '

Prediction failed

'; } } catch (error) { resultsDiv.innerHTML = `

Error: ${error.message}

`; } }); """ # ============================================================ # REACT # ============================================================ react_example = """ // React Component Example import React, { useState } from 'react'; function PneumoniaDetector() { const [file, setFile] = useState(null); const [results, setResults] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const handleFileChange = (e) => { setFile(e.target.files[0]); setResults(null); setError(null); }; const handlePredict = async () => { if (!file) { setError('Please select an image'); return; } setLoading(true); setError(null); const formData = new FormData(); formData.append('file', file); try { const response = await fetch('http://localhost:8000/predict', { method: 'POST', body: formData }); const data = await response.json(); if (data.success) { setResults(data); } else { setError('Prediction failed'); } } catch (err) { setError(`Error: ${err.message}`); } finally { setLoading(false); } }; return (

Pneumonia Detection

{error &&
{error}
} {results && (

Results

SVM Model

Prediction: {results.predictions.svm.class}

Confidence: {(results.predictions.svm.confidence * 100).toFixed(2)}%

CNN Model

Prediction: {results.predictions.cnn.class}

Confidence: {(results.predictions.cnn.confidence * 100).toFixed(2)}%

Consensus: {results.consensus.predicted_class}

Models {results.consensus.agreement ? 'agree' : 'disagree'}

)}
); } export default PneumoniaDetector; """ # ============================================================ # PYTHON REQUESTS # ============================================================ python_requests = """ # Python Example using requests library import requests import json def predict_pneumonia(image_path, api_url='http://localhost:8000'): \"\"\" Send image to API for pneumonia prediction Args: image_path: Path to chest X-ray image api_url: API base URL Returns: Dictionary with prediction results \"\"\" # Prepare file files = {'file': open(image_path, 'rb')} try: # Make request response = requests.post( f'{api_url}/predict', files=files, timeout=30 ) # Parse response if response.status_code == 200: return response.json() else: return { 'success': False, 'error': f'API returned status code {response.status_code}' } except requests.exceptions.RequestException as e: return { 'success': False, 'error': str(e) } finally: files['file'].close() # Usage example if __name__ == '__main__': result = predict_pneumonia('chest_xray.jpg') if result.get('success'): print('Prediction successful!') print(json.dumps(result, indent=2)) svm = result['predictions']['svm'] cnn = result['predictions']['cnn'] print(f"\\nSVM: {svm['class']} ({svm['confidence']:.2%})") print(f"CNN: {cnn['class']} ({cnn['confidence']:.2%})") print(f"\\nConsensus: {result['consensus']['predicted_class']}") else: print(f"Error: {result.get('error')}") """ # ============================================================ # CURL EXAMPLES # ============================================================ curl_examples = """ # cURL Examples # Basic prediction curl -X POST "http://localhost:8000/predict" \\ -H "accept: application/json" \\ -H "Content-Type: multipart/form-data" \\ -F "file=@chest_xray.jpg" # Save response to file curl -X POST "http://localhost:8000/predict" \\ -H "accept: application/json" \\ -H "Content-Type: multipart/form-data" \\ -F "file=@chest_xray.jpg" \\ -o prediction_result.json # Health check curl "http://localhost:8000/health" # Pretty print with jq curl -X POST "http://localhost:8000/predict" \\ -H "accept: application/json" \\ -H "Content-Type: multipart/form-data" \\ -F "file=@chest_xray.jpg" | jq '.' """ # Print examples if __name__ == "__main__": print("=" * 60) print("FRONTEND INTEGRATION EXAMPLES") print("=" * 60) print("\n\n1. VANILLA JAVASCRIPT") print("-" * 60) print(vanilla_js) print("\n\n2. REACT") print("-" * 60) print(react_example) print("\n\n3. PYTHON REQUESTS") print("-" * 60) print(python_requests) print("\n\n4. CURL") print("-" * 60) print(curl_examples)