AronWolverine commited on
Commit
173bba6
·
1 Parent(s): a9de418

commit flask

Browse files
Files changed (3) hide show
  1. app.py +57 -70
  2. dockerfile +10 -15
  3. requirements.txt +5 -5
app.py CHANGED
@@ -1,80 +1,67 @@
1
- import os
2
  import numpy as np
3
- import tensorflow as tf
4
  from tensorflow.keras.models import load_model # type: ignore
5
  from tensorflow.keras.preprocessing import image # type: ignore
6
- from tensorflow.keras.applications.densenet import preprocess_input # type: ignore
7
-
8
- from fastapi import FastAPI, File, UploadFile, Request
9
- from fastapi.templating import Jinja2Templates
10
- from fastapi.responses import HTMLResponse
11
- import uvicorn
12
-
13
- # Initialize FastAPI app
14
- app = FastAPI()
15
-
16
- # Set up template rendering (similar to Flask’s render_template)
17
- templates = Jinja2Templates(directory="templates")
18
-
19
- # Define paths
20
- BASE_DIR = os.path.dirname(__file__)
21
- MODEL_PATH = os.path.join(BASE_DIR, 'uploads', "densenet_ship.h5")
22
-
23
- # Load the model
24
- model = load_model(MODEL_PATH)
25
-
26
- # Define ship categories
27
- val_dict = {
28
- 0: 'Aircraft Carrier',
29
- 1: 'Bulkers',
30
- 2: 'Car Carrier',
31
- 3: 'Container Ship',
32
- 4: 'Cruise',
33
- 5: 'DDG',
34
- 6: 'Recreational',
35
- 7: 'Sailboat',
36
- 8: 'Submarine',
37
- 9: 'Tug'
38
- }
39
-
40
- # Define Routes
41
 
42
- @app.get("/", response_class=HTMLResponse)
43
- async def index(request: Request):
44
- return templates.TemplateResponse("index.html", {"request": request})
45
 
46
- @app.get("/about", response_class=HTMLResponse)
47
- async def about(request: Request):
48
- return templates.TemplateResponse("about.html", {"request": request})
 
 
 
 
49
 
50
- @app.get("/service", response_class=HTMLResponse)
51
- async def service(request: Request):
52
- return templates.TemplateResponse("service.html", {"request": request})
53
 
54
- @app.post("/predict/")
55
- async def predict(image_file: UploadFile = File(...)):
56
- # Save uploaded file
57
- file_path = os.path.join(BASE_DIR, 'uploads', image_file.filename)
58
-
59
- with open(file_path, "wb") as buffer:
60
- buffer.write(await image_file.read())
61
 
62
- # Load and preprocess image
63
- img = image.load_img(file_path, target_size=(224, 224))
64
- img = image.img_to_array(img)
65
- img = img.reshape((1, img.shape[0], img.shape[1], img.shape[2]))
66
- img = preprocess_input(img)
 
 
 
 
 
 
67
 
68
- # Make prediction
69
- pred = model.predict(img)
70
- pred = pred.flatten()
71
-
72
- # Get predicted category
73
- predicted_class = val_dict[np.argmax(pred)]
74
-
75
- # Return result
76
- return {"category": predicted_class, "message": f"The Ship Category is {predicted_class}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
- # Run the FastAPI app with uvicorn (needed when not using Docker Spaces)
79
- if __name__ == "__main__":
80
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
1
  import numpy as np
2
+ import os
3
  from tensorflow.keras.models import load_model # type: ignore
4
  from tensorflow.keras.preprocessing import image # type: ignore
5
+ from tensorflow.keras.layers import Flatten # type: ignore
6
+ from tensorflow.keras.applications.densenet import preprocess_input# type: ignore
7
+ import tensorflow as tf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ from flask import Flask , request, render_template
10
+ #from werkzeug.utils import secure_filename
11
+ #from gevent.pywsgi import WSGIServer
12
 
13
+ app = Flask(__name__)
14
+ basepath = os.path.dirname(__file__)
15
+ modelpath = os.path.join(basepath,'uploads',"densenet_ship.h5")
16
+ model = load_model(modelpath)
17
+ @app.route('/')
18
+ def index():
19
+ return render_template('index.html')
20
 
21
+ @app.route('/about')
22
+ def about():
23
+ return render_template('about.html')
24
 
25
+ @app.route('/service')
26
+ def service():
27
+ return render_template('service.html')
 
 
 
 
28
 
29
+ @app.route('/predict',methods = ['GET','POST'])
30
+ def upload():
31
+ if request.method == 'POST':
32
+ f = request.files['image']
33
+
34
+ #print("current path")
35
+ basepath = os.path.dirname(__file__)
36
+ print("current path", basepath)
37
+ filepath = os.path.join(basepath,'uploads',f.filename)
38
+ print("upload folder is ", filepath)
39
+ f.save(filepath)
40
 
41
+ img=image.load_img(filepath,target_size=(224,224))
42
+ img=image.img_to_array(img)
43
+ img=img.reshape((1,img.shape[0],img.shape[1],img.shape[2]))
44
+ img=preprocess_input(img)
45
+ pred=model.predict(img)
46
+ pred=pred.flatten()
47
+ pred=list(pred)
48
+ n=max(pred)
49
+ val_dict={0: 'Aircraft Carrier',
50
+ 1: 'Bulkers',
51
+ 2: 'Car Carrier',
52
+ 3: 'Container Ship',
53
+ 4: 'Cruise',
54
+ 5: 'DDG',
55
+ 6: 'Recreational',
56
+ 7: 'Sailboat',
57
+ 8: 'Submarine',
58
+ 9: 'Tug'}
59
+ result=val_dict[pred.index(n)]
60
+ print(result)
61
+ text = "the Ship Category is " + result
62
+ return text
63
 
64
+ if __name__ == '__main__':
65
+ app.run(debug = True)
66
+
67
+
dockerfile CHANGED
@@ -1,23 +1,18 @@
1
- # Use official Python runtime
2
  FROM python:3.9
3
 
4
- # Create and switch to a non-root user
5
- RUN useradd -m -u 1000 user
6
- USER user
7
- ENV PATH="/home/user/.local/bin:$PATH"
8
-
9
- # Set working directory inside container
10
  WORKDIR /app
11
 
12
- # Copy requirements file and install dependencies
13
- COPY --chown=user ./requirements.txt requirements.txt
14
- RUN pip install --no-cache-dir --upgrade -r requirements.txt
15
 
16
- # Copy the entire app code
17
- COPY --chown=user . /app
18
 
19
- # Expose port 7860 (used by Hugging Face Spaces)
20
  EXPOSE 7860
21
 
22
- # Run FastAPI app with Uvicorn
23
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
 
1
+ # Use official Python runtime as base image
2
  FROM python:3.9
3
 
4
+ # Set the working directory in the container
 
 
 
 
 
5
  WORKDIR /app
6
 
7
+ # Copy application files to the container
8
+ COPY . .
 
9
 
10
+ # Install required Python packages
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
 
13
+ # Expose Flask port (default: 5000)
14
  EXPOSE 7860
15
 
16
+
17
+ # Command to run the Flask application
18
+ CMD ["gunicorn", "--bind", "0.0.0.0:5000", "app:app"]
requirements.txt CHANGED
@@ -1,6 +1,6 @@
1
- fastapi
2
- uvicorn
3
- tensorflow
4
  numpy
5
- jinja2
6
- pillow
 
 
 
 
 
 
 
1
  numpy
2
+ tensorflow
3
+ keras
4
+ Keras-Preprocessing
5
+ gunicorn
6
+ flask