generated from render-examples/fastapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
234 lines (181 loc) · 6.84 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
from fastapi import FastAPI, HTTPException
from get_lyrics import get_song
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from models import *
from fastapi.responses import JSONResponse
from dotenv import load_dotenv
import os
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
from sqlalchemy.exc import PendingRollbackError
@retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=10), retry=retry_if_exception_type(PendingRollbackError))
def commit_session():
try:
session.commit()
except PendingRollbackError:
session.rollback()
raise
print("\n", "-" * 20)
#### Initialize FastAPI ####
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
#### Setting up database ####
import sqlalchemy as db
from sqlalchemy.engine.reflection import Inspector
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# engine = db.create_engine("sqlite+pysqlite:///./enja.db")
load_dotenv()
db_pass = os.getenv("DATABASE_PASSWORD")
engine = db.create_engine(f"postgresql+psycopg2://postgres.axbrinbwdfzotjdqheek:{db_pass}@aws-0-us-east-1.pooler.supabase.com:6543/postgres")
connection = engine.connect()
inspector = Inspector.from_engine(engine)
Base.metadata.create_all(bind=engine)
Session = sessionmaker(bind=engine)
session = Session()
print(f"Tables in the database found: {inspector.get_table_names()}")
#### Function to fetch song from Genius ####
def fetch_lyrics(song: str, artist: str):
song_data = get_song(song, artist)
if song_data is None:
return -1, ""
return song_data.id, song_data.lyrics
def lyrics_to_list(lyrics):
return list(filter(None, lyrics.split("\n")))[1:]
#### Get all songs ####
@app.get("/get-all-songs/")
async def get_all_songs():
songs = session.query(Song).all()
return songs
#### Get song by id ####
@app.get("/get-song/{song_id}")
async def get_song_by_id(song_id: int):
song = session.query(Song).filter_by(id=song_id).first()
if not song:
raise HTTPException(status_code=404, detail=f"Song with id {id} not found.")
return {
"song_name": song.song_name,
"artist": song.artist,
"id": song_id,
"lyrics": song.lyrics
}
#### Add song to database ####
class AddSongDetails(BaseModel):
song_name: str
artist: str
@app.post("/add-song/")
async def add_song(params: AddSongDetails):
song_id, lyrics = fetch_lyrics(params.song_name, params.artist)
if song_id == -1:
raise HTTPException(status_code=400, detail="Song couldn't be found")
existing_song = session.query(Song).filter_by(id=song_id).first()
if existing_song:
# highlights_by_line = defaultdict(list)
# for highlight in existing_song.highlights:
# highlights_by_line[highlight.line].append({
# "song_id": highlight.song_id,
# "highlighted_text": highlight.highlighted_text,
# "x_pos": highlight.x_pos,
# "start": highlight.start,
# "id": highlight.id,
# "translation": highlight.translation,
# "y_pos": highlight.y_pos,
# "end": highlight.end
# })
highlights = [highlight for highlight in existing_song.highlights]
response_content = {
"message": "Song already exists in database",
"lyrics": existing_song.lyrics,
"id": existing_song.id,
"highlights": highlights
}
return response_content
new_song = Song(
song_name=params.song_name,
artist=params.artist,
lyrics=lyrics,
id=song_id
)
session.add(new_song)
session.commit()
response_content = {
"message": "Song added successfully",
"lyrics": lyrics,
"id": new_song.id,
"highlights": []
}
return response_content
#### Add highlight to database ####
class HighlightDetails(BaseModel):
song_id: int
highlighted_text: str
translation: str
start_index: int
end_index: int
start_line: int
end_line: int
@app.post("/add-highlight/")
async def add_highlight(params: HighlightDetails):
new_highlight = Highlight(
song_id=params.song_id,
highlighted_text=params.highlighted_text,
translation=params.translation,
start_index=params.start_index,
end_index=params.end_index,
start_line=params.start_line,
end_line=params.end_line
)
song = session.query(Song).get(params.song_id)
new_highlight.song = song
session.add(new_highlight)
session.commit()
response_content = {"message": "Highlight added successfully", "highlight_id": new_highlight.id}
return JSONResponse(status_code=201, content=response_content)
#### Get highlights of a song from database ####
@app.get("/get-highlights/{song_id}/")
async def get_highlights(song_id: int):
song = session.query(Song).filter_by(id=song_id).first()
if not song:
raise HTTPException(status_code=404, detail=f"Song with id {song_id} not found.")
# highlights = song.highlights
# highlights_by_line = defaultdict(list)
# for highlight in highlights:
# highlights_by_line[highlight.line].append({
# "song_id": highlight.song_id,
# "highlighted_text": highlight.highlighted_text,
# "x_pos": highlight.x_pos,
# "start": highlight.start,
# "id": highlight.id,
# "translation": highlight.translation,
# "y_pos": highlight.y_pos,
# "end": highlight.end
# })
highlights = [highlight for highlight in song.highlights]
return {"song_id": song_id, "highlights": highlights}
#### Delete a highlight of a song from database ####
@app.delete("/delete-highlight/{highlight_id}")
async def delete_highlight(highlight_id: int):
highlight = session.query(Highlight).filter_by(id=highlight_id).first()
if not highlight:
raise HTTPException(status_code=404, detail=f"Highlight with id {highlight_id} not found.")
session.delete(highlight)
session.commit()
return {"message": "Highlight deleted successfully"}
#### Edit an existing highlight ####
class EditHighlightDetails(BaseModel):
translation: str
@app.put("/edit-highlight/{highlight_id}")
async def edit_highlight(highlight_id: int, params: EditHighlightDetails):
highlight = session.query(Highlight).filter_by(id=highlight_id).first()
if not highlight:
raise HTTPException(status_code=404, detail=f"Highlight with id {highlight_id} not found.")
setattr(highlight, "translation", params.translation)
session.commit()
return {"message": "Highlight edited successfully"}
print("-" * 20)