AntDX316 commited on
Commit
8800810
Β·
1 Parent(s): a1ba68f
Files changed (4) hide show
  1. Dockerfile +16 -0
  2. README.md +7 -5
  3. app.py +54 -36
  4. requirements.txt +5 -5
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
2
+ # you will also find guides on how best to write your Dockerfile
3
+
4
+ FROM python:3.9
5
+
6
+ RUN useradd -m -u 1000 user
7
+ USER user
8
+ ENV PATH="/home/user/.local/bin:$PATH"
9
+
10
+ WORKDIR /app
11
+
12
+ COPY --chown=user ./requirements.txt requirements.txt
13
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
14
+
15
+ COPY --chown=user . /app
16
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
- title: Flask Web App
3
- emoji: 🌐
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: docker
@@ -8,13 +8,14 @@ app_port: 7860
8
  pinned: false
9
  ---
10
 
11
- # Flask Web Application for Hugging Face Spaces
12
 
13
- This is a simple Flask web application deployed on Hugging Face Spaces. It provides:
14
 
15
  - A clean web interface showing the current server time
16
  - A REST API with endpoints for getting the current time and echoing data
17
  - Cross-origin resource sharing (CORS) support for API access from other domains
 
18
 
19
  ## API Endpoints
20
 
@@ -30,12 +31,13 @@ To run this application locally:
30
  pip install -r requirements.txt
31
  ```
32
 
33
- 2. Run the Flask application:
34
  ```
35
  python app.py
36
  ```
37
 
38
  3. Open your browser and navigate to `http://localhost:7860`
 
39
 
40
  ## Deployment
41
 
 
1
  ---
2
+ title: FastAPI Web App
3
+ emoji: πŸš€
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: docker
 
8
  pinned: false
9
  ---
10
 
11
+ # FastAPI Web Application for Hugging Face Spaces
12
 
13
+ This is a simple FastAPI web application deployed on Hugging Face Spaces. It provides:
14
 
15
  - A clean web interface showing the current server time
16
  - A REST API with endpoints for getting the current time and echoing data
17
  - Cross-origin resource sharing (CORS) support for API access from other domains
18
+ - Interactive API documentation via Swagger UI at `/docs`
19
 
20
  ## API Endpoints
21
 
 
31
  pip install -r requirements.txt
32
  ```
33
 
34
+ 2. Run the FastAPI application:
35
  ```
36
  python app.py
37
  ```
38
 
39
  3. Open your browser and navigate to `http://localhost:7860`
40
+ - For API documentation, visit `http://localhost:7860/docs`
41
 
42
  ## Deployment
43
 
app.py CHANGED
@@ -1,45 +1,40 @@
1
- from flask import Flask, render_template, request, jsonify
2
- from flask_cors import CORS
 
 
3
  import os
4
  import datetime
 
 
 
5
 
6
- app = Flask(__name__)
7
- CORS(app) # Enable CORS for all routes
 
 
 
 
 
 
 
 
 
8
 
9
  # Ensure templates directory exists
10
  os.makedirs('templates', exist_ok=True)
11
 
12
- @app.route('/')
13
- def index():
14
- """Render the home page."""
15
- current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
16
- return render_template('index.html', current_time=current_time)
17
-
18
- @app.route('/api/time')
19
- def get_time():
20
- """API endpoint that returns the current time."""
21
- current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
22
- return jsonify({"time": current_time})
23
 
24
- @app.route('/api/echo', methods=['POST'])
25
- def echo():
26
- """API endpoint that echoes back the JSON data sent to it."""
27
- data = request.json
28
- return jsonify({"status": "success", "echo": data})
29
-
30
- if __name__ == '__main__':
31
- # Create templates directory if it doesn't exist
32
- if not os.path.exists('templates'):
33
- os.makedirs('templates')
34
-
35
- # Create a simple HTML template if it doesn't exist
36
- if not os.path.exists('templates/index.html'):
37
- with open('templates/index.html', 'w') as f:
38
- f.write('''
39
  <!DOCTYPE html>
40
  <html>
41
  <head>
42
- <title>Flask Web App on Hugging Face Spaces</title>
43
  <style>
44
  body {
45
  font-family: Arial, sans-serif;
@@ -75,7 +70,7 @@ if __name__ == '__main__':
75
  </style>
76
  </head>
77
  <body>
78
- <h1>Welcome to Flask Web App on Hugging Face Spaces</h1>
79
  <p>The current server time is: {{ current_time }}</p>
80
 
81
  <div class="container">
@@ -122,7 +117,30 @@ if __name__ == '__main__':
122
  </script>
123
  </body>
124
  </html>
125
- ''')
126
-
127
- # Run the Flask app with settings suitable for Hugging Face Spaces
128
- app.run(host='0.0.0.0', port=7860, debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request
2
+ from fastapi.responses import HTMLResponse
3
+ from fastapi.staticfiles import StaticFiles
4
+ from fastapi.templating import Jinja2Templates
5
  import os
6
  import datetime
7
+ from pydantic import BaseModel
8
+ import uvicorn
9
+ from fastapi.middleware.cors import CORSMiddleware
10
 
11
+ # Create FastAPI app
12
+ app = FastAPI(title="FastAPI Web App")
13
+
14
+ # Add CORS middleware
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"],
18
+ allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
 
23
  # Ensure templates directory exists
24
  os.makedirs('templates', exist_ok=True)
25
 
26
+ # Set up templates
27
+ templates = Jinja2Templates(directory="templates")
 
 
 
 
 
 
 
 
 
28
 
29
+ # Create a simple HTML template if it doesn't exist
30
+ if not os.path.exists('templates/index.html'):
31
+ os.makedirs('templates', exist_ok=True)
32
+ with open('templates/index.html', 'w') as f:
33
+ f.write('''
 
 
 
 
 
 
 
 
 
 
34
  <!DOCTYPE html>
35
  <html>
36
  <head>
37
+ <title>FastAPI Web App on Hugging Face Spaces</title>
38
  <style>
39
  body {
40
  font-family: Arial, sans-serif;
 
70
  </style>
71
  </head>
72
  <body>
73
+ <h1>Welcome to FastAPI Web App on Hugging Face Spaces</h1>
74
  <p>The current server time is: {{ current_time }}</p>
75
 
76
  <div class="container">
 
117
  </script>
118
  </body>
119
  </html>
120
+ ''')
121
+
122
+ @app.get("/", response_class=HTMLResponse)
123
+ async def index(request: Request):
124
+ """Render the home page."""
125
+ current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
126
+ return templates.TemplateResponse("index.html", {"request": request, "current_time": current_time})
127
+
128
+ @app.get("/api/time")
129
+ async def get_time():
130
+ """API endpoint that returns the current time."""
131
+ current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
132
+ return {"time": current_time}
133
+
134
+ class EchoRequest(BaseModel):
135
+ """Model for the echo request body."""
136
+ message: str = None
137
+ timestamp: str = None
138
+
139
+ @app.post("/api/echo")
140
+ async def echo(data: EchoRequest):
141
+ """API endpoint that echoes back the JSON data sent to it."""
142
+ return {"status": "success", "echo": data.dict()}
143
+
144
+ # For local development
145
+ if __name__ == '__main__':
146
+ uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
- flask==2.3.3
2
- Werkzeug==2.3.7
3
- flask-cors==4.0.0
4
- transformers==4.25.1
5
- torch==1.13.1
 
1
+ fastapi==0.103.1
2
+ uvicorn[standard]==0.23.2
3
+ jinja2==3.1.2
4
+ python-multipart==0.0.6
5
+ pydantic==2.3.0