Skip to content

Commit

Permalink
refactoring code and setting up api server
Browse files Browse the repository at this point in the history
  • Loading branch information
Aadesh Kulkarni authored and Aadesh Kulkarni committed Jan 10, 2024
1 parent 5ac164f commit 7042e05
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 49 deletions.
66 changes: 22 additions & 44 deletions api/main.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,13 @@
from fastapi import FastAPI, HTTPException, Depends
from fastapi import FastAPI, Depends, UploadFile, Response
from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import List, Annotated
import models
from database import engine, SessionLocal
from sqlalchemy.orm import Session
import os
import sys
from scripts.subtitles import generate_subtitles
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(root_path)

app = FastAPI()
models.Base.metadata.create_all(bind=engine)

def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()


db_dependency = Annotated[Session, Depends(get_db)]


@app.get("/_readyz")
Expand All @@ -25,34 +16,21 @@ def read_root():
return {"status": "ok"}


class Needs(BaseModel):
transcoding: bool
subtitles: bool
thumbnails: bool


class Project(BaseModel):
project: str
videoURL: str
needs: Needs


@app.get("/projects")
async def read_projects(db:db_dependency):
result = db.query(models.Projects).all()
return result

@app.post("/generate-all")
async def create_project(project:Project, db: db_dependency):
# Step 1: Insert project into db
db_project = models.Projects(project=project.project, videoURL=project.videoURL, needTranscoding=project.needs.transcoding, needSubtitles=project.needs.subtitles, needThumbnails=project.needs.thumbnails)
db.add(db_project)
db.commit()
db.refresh(db_project)
@app.post("/subtitles")
def create_subtitles(video_name: str, file: UploadFile):
if not os.path.exists("videos"):
os.makedirs("videos")

# Step 2: Generate transcoding
file_path = f"videos/{video_name}.mp4"
with open(file_path, "wb") as f:
f.write(file.file.read())

# Step 3: Upload to bucket
if not file.content_type.startswith("video/"):
return {"error": "Invalid file type. Only video files are allowed."}

# Step 4: Update table with bucket
return project
if not os.path.exists("output"):
os.makedirs("output")
output_path = generate_subtitles(file_path,"vtt","./output",video_name)
response = FileResponse(output_path, media_type="text/vtt", filename=f"{video_name}.vtt")
response.headers["Content-Disposition"] = f"attachment; filename={video_name}.vtt"
return response
14 changes: 10 additions & 4 deletions api/readme.MD
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,29 @@

### Requirements:
- Python3
- PostgreSQL DB

### Installation:

- Create a new Virtual Environment 'env' using `python3 -m venv env`
- Activate the `env` Environment using `source env/bin/activate`
- Install libraries using `pip install fastapi sqlalchemy psycopg2-binary uvicorn` or `pip install -r requirements.txt`
- Create sanchayai DB and replace your connection string in /api/database.py (postgresql:https://postgres:test123@localhost:5432/sanchayai)
- Install libraries using `pip install -r requirements.txt`

### Run Project:

- python3 run.py
- On your browser: http:https://127.0.0.1:5000/docs

### Routes available

- /subtitles (You can try them at http:https://127.0.0.1:5000/docs )

Future routes:
- /chapters
- /thumbnails


Reference links:
- https://youtu.be/398DuQbQJq0?si=dAW1-QT3bxgZ45Oq
- https://youtu.be/398DuQbQJq0?si=dAW1-QT3bxgZ45Oq (can be ignored for now)


For any queries, add your doubts in the issues section and attach the `question` label to it.
5 changes: 4 additions & 1 deletion api/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ sniffio==1.3.0
SQLAlchemy==2.0.24
starlette==0.32.0.post1
typing_extensions==4.9.0
uvicorn==0.25.0
uvicorn==0.25.0
openai-whisper
tiktoken
openai
18 changes: 18 additions & 0 deletions api/scripts/subtitles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import whisper
from whisper import utils


def generate_subtitles(input_file_path, output_type, output_file_path, output_file_name):
model = whisper.load_model("tiny")
result = model.transcribe(input_file_path)
writer = utils.get_writer(output_type, output_file_path)
writer_args = {
"highlight_words": False,
"max_line_count": None,
"max_line_width": None,
"max_words_per_line": None,
}
writer(result, output_file_name, **writer_args)
output_path = f"{output_file_path}/{output_file_name}.{output_type}"
print("⚡️ Success! ⚡️ Subtitles have been generated @ "+output_path)
return output_path

0 comments on commit 7042e05

Please sign in to comment.