MuhammaJamal commited on
Commit
cc794df
·
verified ·
1 Parent(s): a7b1248

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -57
app.py CHANGED
@@ -1,75 +1,76 @@
1
- import gradio as gr
2
  import tensorflow as tf
3
  import numpy as np
4
  from PIL import Image
 
5
  import json
6
  import os
7
- import io
8
- from fastapi import FastAPI, File, UploadFile
9
- from fastapi.responses import JSONResponse
10
 
11
- # Load model
 
 
12
  def load_model():
13
- model_path = "completeweights.weights.h5"
14
- if os.path.exists(model_path):
15
- return tf.keras.models.load_model(model_path, compile=False)
16
- else:
17
- raise FileNotFoundError(f"{model_path} not found.")
 
 
 
 
 
 
 
 
 
18
 
19
- # Load class names
20
  def load_class_names():
21
- if os.path.exists("class_names.txt"):
22
- with open("class_names.txt", "r") as f:
23
- return [line.strip() for line in f]
24
- elif os.path.exists("class_names.json"):
25
- with open("class_names.json", "r") as f:
26
- return json.load(f)
27
- else:
28
- return [f"Class {i}" for i in range(7)] # fallback
29
 
30
- # Preprocess image
31
- def preprocess_image(image):
32
- image = image.convert("RGB").resize((71, 71))
33
- image = np.array(image) / 255.0
34
- return np.expand_dims(image, axis=0)
35
 
36
- # Predict function
37
- def predict(image):
38
  try:
39
- processed = preprocess_image(image)
40
- prediction = model.predict(processed)[0]
41
- top_idx = np.argmax(prediction)
42
- class_name = class_names[top_idx]
43
- confidence = prediction[top_idx]
44
- return f"✅ {class_name} ({confidence*100:.2f}%)"
45
  except Exception as e:
46
- return f"❌ Error: {str(e)}"
 
47
 
48
- # Load model and classes
49
- model = load_model()
50
- class_names = load_class_names()
 
51
 
52
- # Gradio UI
53
- gr_interface = gr.Interface(
54
- fn=predict,
55
- inputs=gr.Image(type="pil", label="Upload Skin Image"),
56
- outputs=gr.Textbox(label="Prediction"),
57
- title="🧪 Skin Cancer Classifier",
58
- description="Upload a skin lesion image and get a prediction.",
59
- )
60
 
61
- # FastAPI app for backend
62
- fastapi_app = FastAPI()
 
63
 
64
- @fastapi_app.post("/predict")
65
- async def predict_api(file: UploadFile = File(...)):
66
- try:
67
- contents = await file.read()
68
- image = Image.open(io.BytesIO(contents))
69
- result = predict(image)
70
- return JSONResponse(content={"result": result})
71
- except Exception as e:
72
- return JSONResponse(content={"error": str(e)}, status_code=500)
 
 
 
 
 
 
 
73
 
74
- # IMPORTANT: Hugging Face Spaces uses this `app` variable!
75
- app = gr.mount_gradio_app(fastapi_app, gr_interface, path="/")
 
1
+ from flask import Flask, request, jsonify
2
  import tensorflow as tf
3
  import numpy as np
4
  from PIL import Image
5
+ import io
6
  import json
7
  import os
 
 
 
8
 
9
+ app = Flask(__name__)
10
+
11
+ # Load model and class names once at startup
12
  def load_model():
13
+ try:
14
+ if os.path.exists('model.h5'):
15
+ model = tf.keras.models.load_model('model.h5', compile=False)
16
+ return model
17
+ elif os.path.exists('completemodel1 (1).json') and os.path.exists('completeweights.weights.h5'):
18
+ with open('completemodel1 (1).json', 'r') as f:
19
+ model_json = f.read()
20
+ model = tf.keras.models.model_from_json(model_json)
21
+ model.load_weights('completeweights.weights.h5')
22
+ return model
23
+ return None
24
+ except Exception as e:
25
+ print(f"Error loading model: {e}")
26
+ return None
27
 
 
28
  def load_class_names():
29
+ return [
30
+ 'Melanoma', 'Melanocytic nevus', 'Basal cell carcinoma',
31
+ 'Actinic keratosis / Bowen\'s disease', 'Benign keratosis',
32
+ 'Dermatofibroma', 'Vascular lesion'
33
+ ]
 
 
 
34
 
35
+ model = load_model()
36
+ class_names = load_class_names()
 
 
 
37
 
38
+ def preprocess_image(image_bytes):
 
39
  try:
40
+ image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
41
+ image = image.resize((71, 71), Image.Resampling.LANCZOS)
42
+ image_array = np.array(image) / 255.0
43
+ return np.expand_dims(image_array, axis=0)
 
 
44
  except Exception as e:
45
+ print(f"Preprocessing error: {e}")
46
+ return None
47
 
48
+ @app.route('/predict', methods=['POST'])
49
+ def predict():
50
+ if model is None:
51
+ return jsonify({'error': 'Model not loaded'}), 500
52
 
53
+ if 'image' not in request.files:
54
+ return jsonify({'error': 'No image uploaded'}), 400
 
 
 
 
 
 
55
 
56
+ image_file = request.files['image']
57
+ image_bytes = image_file.read()
58
+ processed = preprocess_image(image_bytes)
59
 
60
+ if processed is None:
61
+ return jsonify({'error': 'Image processing failed'}), 500
62
+
63
+ prediction = model.predict(processed)[0]
64
+ idx = np.argmax(prediction)
65
+ confidence = float(prediction[idx])
66
+
67
+ result = {
68
+ 'predicted_class': class_names[idx],
69
+ 'confidence': f"{confidence * 100:.2f}%"
70
+ }
71
+
72
+ return jsonify(result)
73
+
74
+ if __name__ == '__main__':
75
+ app.run(debug=True, host='0.0.0.0', port=5000)
76