Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,13 @@
|
|
1 |
from fastai.vision.all import *
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
# Load the pre-trained model
|
4 |
learn = load_learner('model.pkl')
|
@@ -9,7 +18,85 @@ searches = sorted(searches) # Ensure the categories are in sorted order
|
|
9 |
values = [i for i in range(0, len(searches))]
|
10 |
class_dict = dict(zip(searches, values))
|
11 |
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
# Load the image from the provided path
|
14 |
img = PILImage.create(image_path)
|
15 |
|
@@ -26,7 +113,7 @@ def classify_image(image_path):
|
|
26 |
else:
|
27 |
return {'formal': confidences['formal']}
|
28 |
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
1 |
from fastai.vision.all import *
|
2 |
+
from fastapi import FastAPI, HTTPException
|
3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
4 |
+
import uvicorn
|
5 |
+
import logging
|
6 |
+
import tempfile
|
7 |
+
from pathlib import Path
|
8 |
+
import firebase_admin
|
9 |
+
from firebase_admin import credentials, firestore, storage
|
10 |
+
from pydantic import BaseModel
|
11 |
|
12 |
# Load the pre-trained model
|
13 |
learn = load_learner('model.pkl')
|
|
|
18 |
values = [i for i in range(0, len(searches))]
|
19 |
class_dict = dict(zip(searches, values))
|
20 |
|
21 |
+
# Set up logging
|
22 |
+
logging.basicConfig(level=logging.DEBUG,
|
23 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
24 |
+
logger = logging.getLogger(__name__)
|
25 |
+
|
26 |
+
# Initialize Firebase
|
27 |
+
try:
|
28 |
+
cred = credentials.Certificate("serviceAccountKey.json")
|
29 |
+
firebase_app = firebase_admin.initialize_app(cred, {
|
30 |
+
'storageBucket': 'future-forge-60d3f.appspot.com'
|
31 |
+
})
|
32 |
+
db = firestore.client()
|
33 |
+
bucket = storage.bucket(app=firebase_app)
|
34 |
+
logger.info("Firebase initialized successfully")
|
35 |
+
except Exception as e:
|
36 |
+
logger.error(f"Failed to initialize Firebase: {str(e)}")
|
37 |
+
|
38 |
+
app = FastAPI()
|
39 |
+
|
40 |
+
# Add CORS middleware
|
41 |
+
app.add_middleware(
|
42 |
+
CORSMiddleware,
|
43 |
+
allow_origins=["*"],
|
44 |
+
allow_credentials=True,
|
45 |
+
allow_methods=["*"],
|
46 |
+
allow_headers=["*"],
|
47 |
+
)
|
48 |
+
|
49 |
+
|
50 |
+
# Define the input model
|
51 |
+
class FileProcess(BaseModel):
|
52 |
+
file_path: str
|
53 |
+
|
54 |
+
|
55 |
+
@app.post("/process")
|
56 |
+
async def process_file(file_data: FileProcess):
|
57 |
+
logger.info(f"Processing file from Firebase Storage: {file_data.file_path}")
|
58 |
+
|
59 |
+
try:
|
60 |
+
# Get the file from Firebase Storage
|
61 |
+
blob = bucket.blob(file_data.file_path)
|
62 |
+
|
63 |
+
# Create a temporary file
|
64 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=f".{file_data.file_path.split('.')[-1]}") as tmp_file:
|
65 |
+
blob.download_to_filename(tmp_file.name)
|
66 |
+
tmp_file_path = Path(tmp_file.name)
|
67 |
+
|
68 |
+
logger.info(f"File downloaded temporarily at: {tmp_file_path}")
|
69 |
+
|
70 |
+
file_type = file_data.file_path.split('.')[-1].lower()
|
71 |
+
|
72 |
+
try:
|
73 |
+
if file_type in ['jpg', 'jpeg', 'png', 'bmp']:
|
74 |
+
output = process_video(str(tmp_file_path))
|
75 |
+
result = {"type": "image", "data": {"result": output}}
|
76 |
+
else:
|
77 |
+
raise HTTPException(status_code=400, detail="Unsupported file type")
|
78 |
+
|
79 |
+
logger.info(f"Processing complete. Result: {result}")
|
80 |
+
|
81 |
+
# Store result in Firebase
|
82 |
+
try:
|
83 |
+
doc_ref = db.collection('results').add(result)
|
84 |
+
return {"message": "File processed successfully", "result": result}
|
85 |
+
except Exception as e:
|
86 |
+
logger.error(f"Failed to store result in Firebase: {str(e)}")
|
87 |
+
return {"message": "File processed successfully, but failed to store in Firebase", "result": result,
|
88 |
+
"error": str(e)}
|
89 |
+
|
90 |
+
finally:
|
91 |
+
# Clean up the temporary file
|
92 |
+
tmp_file_path.unlink()
|
93 |
+
|
94 |
+
except Exception as e:
|
95 |
+
logger.error(f"Error processing file: {str(e)}")
|
96 |
+
raise HTTPException(status_code=500, detail=f"Error processing file: {str(e)}")
|
97 |
+
|
98 |
+
|
99 |
+
def process_video(video_path):
|
100 |
# Load the image from the provided path
|
101 |
img = PILImage.create(image_path)
|
102 |
|
|
|
113 |
else:
|
114 |
return {'formal': confidences['formal']}
|
115 |
|
116 |
+
|
117 |
+
if __name__ == "__main__":
|
118 |
+
logger.info("Starting the Face Emotion Recognition API")
|
119 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|