iwin10s commited on
Commit
0cd65f4
·
verified ·
1 Parent(s): 15e7717

Upload 6 files

Browse files

necessary files for deployment

Files changed (6) hide show
  1. api_app.py +62 -0
  2. app.py +13 -0
  3. config.json +33 -0
  4. model.safetensors +3 -0
  5. preprocessor_config.json +33 -0
  6. requirements.txt +7 -0
api_app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile
2
+ from transformers import ViTForImageClassification, AutoImageProcessor
3
+ from transformers import pipeline
4
+ import io
5
+ from PIL import Image
6
+ import torch
7
+ import os
8
+
9
+ # --- Setup ---
10
+ app = FastAPI()
11
+ # Define the path where the model files will be located in the deployed environment
12
+ MODEL_PATH = "." # In Hugging Face Spaces, files are often in the root directory
13
+
14
+ # Load model and processor outside the endpoint for speed
15
+ try:
16
+ processor = AutoImageProcessor.from_pretrained(MODEL_PATH)
17
+ model = ViTForImageClassification.from_pretrained(MODEL_PATH)
18
+ except Exception as e:
19
+ # A fallback/debug print if loading fails during deployment
20
+ print(f"Error loading model or processor from {MODEL_PATH}: {e}")
21
+ # You might need to check file names or adjust MODEL_PATH if this fails
22
+
23
+ device = "cuda" if torch.cuda.is_available() else "cpu"
24
+ model.to(device)
25
+ model.eval()
26
+
27
+ # --- Prediction Endpoint ---
28
+ @app.post("/predict")
29
+ async def predict(file: UploadFile = File(...)):
30
+ """Accepts an image file and returns the probability of a leak."""
31
+ try:
32
+ # 1. Read the uploaded file bytes
33
+ data = await file.read()
34
+
35
+ # 2. Open the image using PIL
36
+ img = Image.open(io.BytesIO(data)).convert("RGB")
37
+
38
+ # 3. Preprocess the image (resize, normalize)
39
+ inputs = processor(images=img, return_tensors="pt")
40
+ inputs = {k:v.to(device) for k,v in inputs.items()}
41
+
42
+ # 4. Run inference
43
+ with torch.no_grad():
44
+ outputs = model(**inputs)
45
+ # Apply softmax to get probabilities
46
+ probs = torch.softmax(outputs.logits, dim=-1).cpu().numpy()[0]
47
+
48
+ # The 'leak' label has ID 1 (based on your id2label = {0: "no_leak", 1: "leak"})
49
+ prob_leak = float(probs[1])
50
+
51
+ return {
52
+ "prediction": "leak" if prob_leak >= 0.5 else "no_leak",
53
+ "leak_probability": prob_leak
54
+ }
55
+
56
+ except Exception as e:
57
+ return {"error": str(e), "message": "Prediction failed."}
58
+
59
+ # --- Root Endpoint (for health check) ---
60
+ @app.get("/")
61
+ def home():
62
+ return {"status": "Model API is running"}
app.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from subprocess import Popen
3
+
4
+ # This script tells the Hugging Face environment to run your FastAPI app
5
+ # on the correct port, which is necessary when using the Gradio SDK template.
6
+
7
+ # Set the port FastAPI should listen on (HF requires 7860)
8
+ os.environ['PORT'] = '7860'
9
+
10
+ # Start the uvicorn server to host the FastAPI application
11
+ # api_app:app refers to the 'app' variable inside your 'api_app.py' file
12
+ # --host 0.0.0.0 is necessary for external access
13
+ Popen(["uvicorn", "api_app:app", "--host", "0.0.0.0", "--port", "7860"])
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ViTForImageClassification"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.0,
6
+ "dtype": "float32",
7
+ "encoder_stride": 16,
8
+ "hidden_act": "gelu",
9
+ "hidden_dropout_prob": 0.0,
10
+ "hidden_size": 768,
11
+ "id2label": {
12
+ "0": "no_leak",
13
+ "1": "leak"
14
+ },
15
+ "image_size": 224,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 3072,
18
+ "label2id": {
19
+ "leak": 1,
20
+ "no_leak": 0
21
+ },
22
+ "layer_norm_eps": 1e-12,
23
+ "model_type": "vit",
24
+ "num_attention_heads": 12,
25
+ "num_channels": 3,
26
+ "num_hidden_layers": 12,
27
+ "patch_size": 16,
28
+ "pooler_act": "tanh",
29
+ "pooler_output_size": 768,
30
+ "problem_type": "single_label_classification",
31
+ "qkv_bias": true,
32
+ "transformers_version": "4.57.2"
33
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00f8294b61d9e6fb879e401172c44b5fa2cbfff6a906a1d72a3a5e130725a977
3
+ size 343223968
preprocessor_config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": null,
3
+ "data_format": "channels_first",
4
+ "default_to_square": true,
5
+ "device": null,
6
+ "disable_grouping": null,
7
+ "do_center_crop": null,
8
+ "do_convert_rgb": null,
9
+ "do_normalize": true,
10
+ "do_pad": null,
11
+ "do_rescale": true,
12
+ "do_resize": true,
13
+ "image_mean": [
14
+ 0.5,
15
+ 0.5,
16
+ 0.5
17
+ ],
18
+ "image_processor_type": "ViTImageProcessorFast",
19
+ "image_std": [
20
+ 0.5,
21
+ 0.5,
22
+ 0.5
23
+ ],
24
+ "input_data_format": null,
25
+ "pad_size": null,
26
+ "resample": 2,
27
+ "rescale_factor": 0.00392156862745098,
28
+ "return_tensors": null,
29
+ "size": {
30
+ "height": 224,
31
+ "width": 224
32
+ }
33
+ }
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ transformers
4
+ datasets
5
+ torch
6
+ pillow
7
+ scikit-learn