jsijan commited on
Commit
423db94
Β·
verified Β·
1 Parent(s): 63b1f42

Upload main.py

Browse files
Files changed (1) hide show
  1. app/main.py +230 -0
app/main.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ import torch
4
+ import timm
5
+ from PIL import Image
6
+ from torchvision import transforms
7
+ import io
8
+ import os
9
+ import requests
10
+
11
+ app = FastAPI()
12
+
13
+ app.add_middleware(
14
+ CORSMiddleware,
15
+ allow_origins=["*"],
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
+ CLASS_NAMES = ['back', 'front', 'left-side', 'right-side', 'tachometer', 'unknown']
22
+ NUM_CLASSES = len(CLASS_NAMES)
23
+ MODEL_PATH = "angle_classifier_convnext.pt"
24
+ MODEL_URL = "https://huggingface.co/jsijan/car-angle-model/resolve/main/angle_classifier_convnext.pt"
25
+
26
+ # πŸ“¦ Load model
27
+ model = None
28
+ try:
29
+ if not os.path.exists(MODEL_PATH):
30
+ print("πŸ“₯ Downloading model from Hugging Face...")
31
+ r = requests.get(MODEL_URL)
32
+ with open(MODEL_PATH, "wb") as f:
33
+ f.write(r.content)
34
+
35
+ print("🧠 Loading model...")
36
+ model = timm.create_model('convnext_base', pretrained=False, num_classes=NUM_CLASSES)
37
+ model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
38
+ model.to(DEVICE)
39
+ model.eval()
40
+ print("βœ… Model ready.")
41
+ except Exception as e:
42
+ print(f"❌ Model loading failed: {e}")
43
+
44
+ transform = transforms.Compose([
45
+ transforms.Resize((224, 224)),
46
+ transforms.ToTensor(),
47
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
48
+ std=[0.229, 0.224, 0.225])
49
+ ])
50
+
51
+ @app.get("/")
52
+ def root():
53
+ return {"message": "API running", "model_loaded": model is not None}
54
+
55
+ @app.post("/predict")
56
+ async def predict(file: UploadFile = File(...)):
57
+ if model is None:
58
+ return {"error": "Model not loaded"}
59
+
60
+ image_bytes = await file.read()
61
+ image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
62
+ input_tensor = transform(image).unsqueeze(0).to(DEVICE)
63
+
64
+ with torch.no_grad():
65
+ outputs = model(input_tensor)
66
+ probs = torch.nn.functional.softmax(outputs[0], dim=0)
67
+
68
+ top_prob, top_class = torch.max(probs, 0)
69
+ return {
70
+ "prediction": CLASS_NAMES[top_class],
71
+ "confidence": f"{top_prob.item():.2f}",
72
+ "all_confidences": {
73
+ CLASS_NAMES[i]: round(probs[i].item(), 4) for i in range(NUM_CLASSES)
74
+ }
75
+ }
76
+
77
+ # from fastapi import FastAPI, UploadFile, File
78
+ # from fastapi.middleware.cors import CORSMiddleware
79
+ # import torch
80
+ # import timm
81
+ # from PIL import Image
82
+ # from torchvision import transforms
83
+ # import io
84
+ # import os
85
+
86
+ # app = FastAPI()
87
+
88
+ # # CORS
89
+ # app.add_middleware(
90
+ # CORSMiddleware,
91
+ # allow_origins=["*"],
92
+ # allow_methods=["*"],
93
+ # allow_headers=["*"],
94
+ # )
95
+
96
+ # # πŸ“¦ Config
97
+ # DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
98
+ # CLASS_NAMES = ['back', 'front', 'left-side', 'right-side', 'tachometer', 'unknown']
99
+ # NUM_CLASSES = len(CLASS_NAMES)
100
+ # MODEL_PATH = "angle_classifier_convnext.pt"
101
+ # GDRIVE_ID = "16vAuLUiL9Jy-S0eIie7oFoawDHavLZQ9"
102
+ # GDRIVE_URL = f"https://drive.google.com/uc?id={GDRIVE_ID}"
103
+
104
+ # # Load model
105
+ # model = None
106
+ # try:
107
+ # if not os.path.exists(MODEL_PATH):
108
+ # import gdown
109
+ # print("πŸ“¦ Downloading model from Google Drive...")
110
+ # gdown.download(GDRIVE_URL, MODEL_PATH, quiet=False)
111
+
112
+ # print("🧠 Loading convnext_base...")
113
+ # model = timm.create_model('convnext_base', pretrained=False, num_classes=NUM_CLASSES)
114
+ # model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
115
+ # model.to(DEVICE)
116
+ # model.eval()
117
+ # print("βœ… Model loaded.")
118
+ # except Exception as e:
119
+ # print(f"❌ Error loading model: {e}")
120
+
121
+ # # πŸ” Transform
122
+ # transform = transforms.Compose([
123
+ # transforms.Resize((224, 224)),
124
+ # transforms.ToTensor(),
125
+ # transforms.Normalize(mean=[0.485, 0.456, 0.406],
126
+ # std=[0.229, 0.224, 0.225])
127
+ # ])
128
+
129
+ # @app.get("/")
130
+ # def root():
131
+ # return {"message": "API is running", "model_loaded": model is not None}
132
+
133
+ # @app.post("/predict")
134
+ # async def predict(file: UploadFile = File(...)):
135
+ # if model is None:
136
+ # return {"error": "Model not loaded."}
137
+
138
+ # image_bytes = await file.read()
139
+ # image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
140
+ # input_tensor = transform(image).unsqueeze(0).to(DEVICE)
141
+
142
+ # with torch.no_grad():
143
+ # outputs = model(input_tensor)
144
+ # probs = torch.nn.functional.softmax(outputs[0], dim=0)
145
+
146
+ # top_prob, top_class = torch.max(probs, 0)
147
+ # return {
148
+ # "prediction": CLASS_NAMES[top_class],
149
+ # "confidence": f"{top_prob.item():.2f}",
150
+ # "all_confidences": {
151
+ # CLASS_NAMES[i]: round(probs[i].item(), 4) for i in range(NUM_CLASSES)
152
+ # }
153
+ # }
154
+
155
+ # # from fastapi import FastAPI, UploadFile, File
156
+ # # from fastapi.middleware.cors import CORSMiddleware
157
+ # # import torch
158
+ # # import timm
159
+ # # from PIL import Image
160
+ # # from torchvision import transforms
161
+ # # import io
162
+ # # import os
163
+ # # import gdown
164
+
165
+ # # app = FastAPI()
166
+
167
+ # # # CORS for React frontend
168
+ # # app.add_middleware(
169
+ # # CORSMiddleware,
170
+ # # allow_origins=["*"], # or restrict to your frontend URL
171
+ # # allow_methods=["*"],
172
+ # # allow_headers=["*"],
173
+ # # )
174
+ # # @app.get("/")
175
+ # # def root():
176
+ # # return {"message": "API is running (no model loaded)"}
177
+
178
+ # # # # Load model
179
+ # # DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
180
+ # # # = ['back', 'front', 'left-side', 'right-side', 'tachometer', 'unknown']
181
+ # # # NUM_CLASSES = len()
182
+
183
+ # # # model = timm.create_model('convnext_base', pretrained=False, num_classes=NUM_CLASSES)
184
+ # # # model.load_state_dict(torch.load("angle_classifier_convnext.pt", map_location=DEVICE))
185
+ # # # model.to(DEVICE)
186
+ # # # model.eval()
187
+
188
+ # # # https://drive.google.com/file/d/16vAuLUiL9Jy-S0eIie7oFoawDHavLZQ9/view?usp=sharing
189
+
190
+ # # MODEL_PATH = "angle_classifier_convnext.pt"
191
+ # # GDRIVE_ID = "16vAuLUiL9Jy-S0eIie7oFoawDHavLZQ9"
192
+ # # GDRIVE_URL = f"https://drive.google.com/uc?id={GDRIVE_ID}"
193
+
194
+ # # if not os.path.exists(MODEL_PATH):
195
+ # # print("πŸ“¦ Model not found, downloading from Google Drive...")
196
+ # # gdown.download(GDRIVE_URL, MODEL_PATH, quiet=False, use_cookies=True)
197
+
198
+ # # model = timm.create_model('convnext_base', pretrained=False, num_classes=NUM_CLASSES)
199
+ # # model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
200
+ # # model.to(DEVICE)
201
+ # # model.eval()
202
+ # # print("βœ… Model loaded")
203
+
204
+ # # #
205
+ # # transform = transforms.Compose([
206
+ # # transforms.Resize((224, 224)),
207
+ # # transforms.ToTensor(),
208
+ # # transforms.Normalize(mean=[0.485, 0.456, 0.406],
209
+ # # std=[0.229, 0.224, 0.225])
210
+ # # ])
211
+
212
+ # # @app.post("/predict")
213
+ # # async def predict(file: UploadFile = File(...)):
214
+ # # image_bytes = await file.read()
215
+ # # image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
216
+ # # input_tensor = transform(image).unsqueeze(0).to(DEVICE)
217
+
218
+ # # with torch.no_grad():
219
+ # # outputs = model(input_tensor)
220
+ # # probs = torch.nn.functional.softmax(outputs[0], dim=0)
221
+
222
+ # # top_prob, top_class = torch.max(probs, 0)
223
+
224
+ # # return {
225
+ # # "prediction": [top_class],
226
+ # # "confidence": f"{top_prob.item():.2f}",
227
+ # # "all_confidences": {
228
+ # # [i]: round(probs[i].item(), 4) for i in range(NUM_CLASSES)
229
+ # # }
230
+ # # }