Subhraj07 commited on
Commit
e480c72
·
1 Parent(s): ec79a93

initial commit

Browse files
Files changed (8) hide show
  1. .gitattributes +0 -1
  2. .gitignore +1 -0
  3. .token.json +0 -0
  4. Dockerfile +32 -0
  5. README.md +57 -3
  6. app.py +96 -0
  7. requirements.txt +8 -0
  8. utils.py +22 -0
.gitattributes CHANGED
@@ -25,7 +25,6 @@
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
  *.wasm filter=lfs diff=lfs merge=lfs -text
 
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
 
28
  *.tflite filter=lfs diff=lfs merge=lfs -text
29
  *.tgz filter=lfs diff=lfs merge=lfs -text
30
  *.wasm filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__
.token.json ADDED
File without changes
Dockerfile ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use the official Python 3.9 image
2
+ FROM python:3.9
3
+
4
+ RUN apt update && apt-get install -y ffmpeg apt-utils build-essential gcc && rm -rf /var/lib/apt/lists/*
5
+
6
+ # Set the working directory to /code
7
+ WORKDIR /code
8
+
9
+ # Copy the current directory contents into the container at /code
10
+ COPY ./requirements.txt /code/requirements.txt
11
+
12
+ # Install requirements.txt
13
+ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
14
+
15
+ # Set up a new user named "user" with user ID 1000
16
+ RUN useradd -m -u 1000 user
17
+ # Switch to the "user" user
18
+ USER user
19
+ # Set home to the user's home directory
20
+ ENV HOME=/home/user \
21
+ PATH=/home/user/.local/bin:$PATH
22
+
23
+ # Set the working directory to the user's home directory
24
+ WORKDIR $HOME/app
25
+
26
+ # Copy the current directory contents into the container at $HOME/app setting the owner to the user
27
+ COPY --chown=user . $HOME/app
28
+
29
+ # Start the FastAPI app on port 7860, the default port expected by Spaces
30
+ # CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
31
+
32
+ CMD gunicorn -k uvicorn.workers.UvicornWorker --workers 2 --threads=2 --max-requests 512 --bind 0.0.0.0:7860 app:app
README.md CHANGED
@@ -1,10 +1,64 @@
1
  ---
2
- title: Transcription Api
3
  emoji: 🔥
4
  colorFrom: purple
5
- colorTo: gray
6
  sdk: docker
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Chatapi
3
  emoji: 🔥
4
  colorFrom: purple
5
+ colorTo: purple
6
  sdk: docker
7
  pinned: false
8
+ license: apache-2.0
9
+ duplicated_from: Subhraj07/chatapi
10
  ---
11
 
12
+ ## How to Use the API using python
13
+
14
+ ### Create a Token
15
+ ```
16
+ import requests
17
+
18
+ headers = {
19
+ 'accept': 'application/json',
20
+ 'Content-Type': 'application/json',
21
+ }
22
+
23
+ json_data = {
24
+ "ref_key": "F0eeQ419wvoCSPH7KBmsd9OiVkF0W0DxK1XE9T3BlbkFJ0",
25
+ "expiry_date": "2023-06-15"
26
+ }
27
+
28
+ response = requests.post('https://subhraj07-chatapi.hf.space/create', headers=headers, json=json_data)
29
+ token = response.json()
30
+ ```
31
+ ### calling open API (text-davinci-002/gpt-3.5-turbo)
32
+ ```
33
+ import requests
34
+
35
+ headers = {
36
+ 'accept': 'application/json',
37
+ 'Content-Type': 'application/json',
38
+ 'Authorization': 'Bearer TOKEN',
39
+ }
40
+
41
+ json_data = {
42
+ 'data': []
43
+ }
44
+
45
+ response = requests.post('https://subhraj07-chatapi.hf.space/transcribe', headers=headers, json=json_data)
46
+ if response.status_code == 200:
47
+ print(response.json())
48
+ ```
49
+
50
+ ### Check list of tokens
51
+ ```
52
+ import requests
53
+
54
+ headers = {
55
+ 'accept': 'application/json',
56
+ 'Content-Type': 'application/json',
57
+ 'Authorization': 'Bearer TOKEN
58
+ }
59
+
60
+ response = requests.get('https://subhraj07-chatapi.hf.space/list', headers=headers)
61
+ print(response.json())
62
+
63
+ ```
64
+
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ from fastapi import FastAPI, HTTPException
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from pydantic import BaseModel
5
+ import pydantic
6
+ from fastapi import FastAPI, HTTPException, Depends, Request, Response
7
+ from fastapi.security import OAuth2PasswordBearer
8
+ from tinydb import TinyDB
9
+ from tinydb import Query
10
+ from datetime import datetime
11
+ from utils import generate_token
12
+ import whisper
13
+ import numpy as np
14
+ from typing import List
15
+
16
+ model = whisper.load_model("medium")
17
+ # model = whisper.load_model("base")
18
+
19
+ query = Query()
20
+ db = TinyDB(".token.json")
21
+
22
+ app = FastAPI()
23
+
24
+ origins = ["*"]
25
+
26
+ app.add_middleware(
27
+ CORSMiddleware,
28
+ allow_origins=origins,
29
+ allow_credentials=True,
30
+ allow_methods=["*"],
31
+ allow_headers=["*"],
32
+ )
33
+
34
+ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
35
+
36
+ REF_KEY = "F0eeQ419wvoCSPH7KBmsd9OiVkF0W0DxK1XE9T3BlbkFJ0"
37
+ model_name = ""
38
+
39
+ def verify_token(token: str = Depends(oauth2_scheme)):
40
+ expiry = -1
41
+ res = db.get(query.token == token)
42
+
43
+ if res:
44
+ expiry = (datetime.strptime(res["expiry_date"], '%Y-%m-%d') - datetime.strptime(res["created_at"], '%Y-%m-%d')).days
45
+
46
+ if expiry < 0:
47
+ return {"message": "Token is not Valid"}
48
+
49
+ return token
50
+
51
+
52
+ class AudioInput(BaseModel):
53
+ data: List
54
+
55
+ class RefToken(BaseModel):
56
+ expiry_date: str
57
+ ref_key: str
58
+
59
+ @app.get("/")
60
+ async def base_url():
61
+ try:
62
+ return {
63
+ "Please Check the documentation here": "https://huggingface.co/spaces/Subhraj07/chatapi/blob/main/README.md",
64
+ "Swagger UI" : "https://subhraj07-chatapi.hf.space/docs"
65
+ }
66
+ except Exception as e:
67
+ raise HTTPException(status_code=500, detail="An error occurred while processing the request." + str(e))
68
+
69
+ @app.post("/create")
70
+ async def create(data: RefToken):
71
+ token = "Reference Key is incorrect"
72
+ try:
73
+ if data.ref_key == REF_KEY:
74
+ token = generate_token(data.expiry_date, db)
75
+ return {"TOKEN": token}
76
+ except Exception as e:
77
+ raise HTTPException(status_code=500, detail="An error occurred while processing the request." + str(e))
78
+
79
+ @app.get("/list")
80
+ async def list(token: str = Depends(verify_token)):
81
+ try:
82
+ data = db.all()
83
+ return {"data": data}
84
+ except Exception as e:
85
+ raise HTTPException(status_code=500, detail="An error occurred while processing the request." + str(e))
86
+
87
+ @app.post("/transcribe")
88
+ async def chat(audio_input: AudioInput, token: str = Depends(verify_token)):
89
+ try:
90
+ transcription = model.transcribe(np.asarray(audio_input))
91
+
92
+ return {
93
+ "transcript": transcription["text"]
94
+ }
95
+ except Exception as e:
96
+ raise HTTPException(status_code=500, detail="An error occurred while processing the request." + str(e))
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.95.1
2
+ uvicorn==0.22.0
3
+ openai==0.27.6
4
+ tinydb==4.7.1
5
+ gunicorn==20.1.0
6
+ uvloop==0.15.2
7
+ httptools==0.2.0
8
+ git+https://github.com/openai/whisper.git
utils.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timedelta, date
2
+ import secrets
3
+ import random
4
+ import string
5
+
6
+
7
+ def generate_token(expiry_date, db):
8
+ alphabet = string.ascii_letters # Get a string containing all the alphabets (both upper and lower case)
9
+ first_char = random.choice(alphabet) # Randomly choose an alphabet as the first character
10
+ token = "md-" + first_char + secrets.token_hex(60)
11
+
12
+ creation_date = date.today().strftime("%Y-%m-%d")
13
+
14
+ token_details = {
15
+ "created_at": creation_date,
16
+ "expiry_date" : expiry_date,
17
+ "token" : token
18
+ }
19
+
20
+ db.insert(token_details)
21
+
22
+ return token