File size: 5,520 Bytes
31df1ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
"""
Simple local FastAPI server for testing face recognition
Run this to test the web interface locally
"""

import sys
import os
from pathlib import Path

# Add the parent directory to Python path
sys.path.append(str(Path(__file__).resolve().parent.parent))

from fastapi import FastAPI, Request, File, UploadFile
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import numpy as np
from PIL import Image
import uvicorn

# Import face recognition
from app.Hackathon_setup import face_recognition

app = FastAPI(title="Local Face Recognition Test")

# Mount static files
app.mount("/static", StaticFiles(directory="app/static"), name="static")

# Templates
templates = Jinja2Templates(directory="app/templates")

@app.get("/", response_class=HTMLResponse)
async def root():
    """Simple HTML interface for testing"""
    html_content = """
    <!DOCTYPE html>
    <html>
    <head>
        <title>Face Recognition Test</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 40px; }
            .container { max-width: 600px; margin: 0 auto; }
            .form-group { margin: 20px 0; }
            input[type="file"] { margin: 10px 0; }
            button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; }
            button:hover { background: #0056b3; }
            .result { margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 5px; }
            .error { background: #f8d7da; color: #721c24; }
            .success { background: #d4edda; color: #155724; }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>🧠 Face Recognition Test</h1>
            <p>Upload a face image to test the classification locally.</p>
            
            <form action="/predict" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="file">Select Face Image:</label><br>
                    <input type="file" id="file" name="file" accept="image/*" required>
                </div>
                <button type="submit">πŸ” Classify Face</button>
            </form>
            
            <div id="result"></div>
        </div>
        
        <script>
            document.querySelector('form').addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const formData = new FormData();
                const fileInput = document.getElementById('file');
                formData.append('file', fileInput.files[0]);
                
                const resultDiv = document.getElementById('result');
                resultDiv.innerHTML = '<div class="result">Processing...</div>';
                
                try {
                    const response = await fetch('/predict', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.text();
                    
                    if (result.includes('UNKNOWN_CLASS')) {
                        resultDiv.innerHTML = `<div class="result error">❌ Result: ${result}</div>`;
                    } else if (result.includes('Person')) {
                        resultDiv.innerHTML = `<div class="result success">βœ… Result: ${result}</div>`;
                    } else {
                        resultDiv.innerHTML = `<div class="result">πŸ“‹ Result: ${result}</div>`;
                    }
                } catch (error) {
                    resultDiv.innerHTML = `<div class="result error">❌ Error: ${error.message}</div>`;
                }
            });
        </script>
    </body>
    </html>
    """
    return HTMLResponse(content=html_content)

@app.post("/predict")
async def predict_face(file: UploadFile = File(...)):
    """Predict face class from uploaded image"""
    try:
        # Save uploaded file
        contents = await file.read()
        filename = f"app/static/{file.filename}"
        
        with open(filename, 'wb') as f:
            f.write(contents)
        
        # Load and process image
        img = Image.open(filename)
        img_array = np.array(img).reshape(img.size[1], img.size[0], 3).astype(np.uint8)
        
        # Get face class
        result = face_recognition.get_face_class(img_array)
        
        return f"Predicted Face Class: {result}"
        
    except Exception as e:
        return f"Error: {str(e)}"

@app.get("/test")
async def test_endpoint():
    """Simple test endpoint"""
    try:
        from app.Hackathon_setup.face_recognition import CLASS_NAMES
        import joblib
        
        # Test model loading
        classifier = joblib.load('app/Hackathon_setup/decision_tree_model.sav')
        scaler = joblib.load('app/Hackathon_setup/face_recognition_scaler.sav')
        
        return {
            "status": "success",
            "class_names": CLASS_NAMES,
            "classifier_classes": classifier.classes_.tolist(),
            "scaler_features": scaler.n_features_in_
        }
    except Exception as e:
        return {"status": "error", "message": str(e)}

if __name__ == "__main__":
    print("Starting local Face Recognition test server...")
    print("Open your browser and go to: http://localhost:8000")
    print("Press Ctrl+C to stop the server")
    
    uvicorn.run(app, host="0.0.0.0", port=8000)