From 5108346a4636d1da845fb83a164b1b7085b34b42 Mon Sep 17 00:00:00 2001 From: julius Date: Sun, 18 Jun 2023 13:09:16 +0000 Subject: [PATCH] FastAPI --- main.py | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 main.py diff --git a/main.py b/main.py new file mode 100644 index 00000000..e98b0c6e --- /dev/null +++ b/main.py @@ -0,0 +1,95 @@ +import random +from pathlib import Path + +import uvicorn +from fastapi import FastAPI, Response +from fastapi.middleware.cors import CORSMiddleware +from sqlmodel import Session, select, text + +from mw_scraper import Sense, Word, engine + +app = FastAPI(title="Phrases API", root_path="/api") +origins = [ + "http://localhost", + "http://localhost:3000", + "https://localhost", + "https://0124816.xyz", + "http://0124816.xyz:3001", +] + +app.add_middleware( + CORSMiddleware, + allow_origins=origins, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + + +@app.get("/allwords/", response_model=list[str]) +def words(): + with Session(engine) as session: + results = session.exec(select(Word.word)).all() + return results + + +@app.get("/randomword/", response_model=str) +def words(): + with Session(engine) as session: + stmt = select(Word.word).order_by(text("random()")).limit(1) + results = session.exec(stmt).one() + return results + + +def random_char(): + chars = list("@$#%^&-_*;,~") + return random.choice(chars) + + +@app.get("/phrases/", response_model=list[str]) +def phrases(n: int = 4, nouns: int = 1, adjs: int = 2, pw: bool = False): + n, nouns, adjs = map(abs, [n, nouns, adjs]) + nouns = nouns if nouns <= 4 else 16 + adjs = adjs if adjs <= 4 else 16 + n = n if n <= 200 else 200 + + with Session(engine) as session: + stmt = ( + select(Sense.word) + .where(Sense.word_class == "adjective") + .where(text("sense.word !~ '\s|-'")) + .order_by(text("random()")) + .limit(n * adjs) + ) + l_adjectives = session.exec(stmt).all() + + stmt = ( + select(Sense.word) + .where(Sense.word_class == "noun") + .where(text("sense.word !~ '\s'")) + .order_by(text("random()")) + .limit(n * nouns) + ) + l_nouns = session.exec(stmt).all() + phrases = [ + l_adjectives[i * adjs : (i + 1) * adjs] + + l_nouns[i * nouns : (i + 1) * nouns] + for i in range(n) + ] + + if pw: + # ps = [ "".join(p)[:-1] for p in [ [word + char for word, char in zip(p, [random_char() for w in p])] for p in phrases ] ] + ps = [ + "".join([w.capitalize() for w,i in enumerate(p) if i > 0]) + + random_char() + + f"{random.randint(0,999):03d}" + for p in phrases + ] + else: + ps = [" ".join(p) for p in phrases] + + return ps + + +if __name__ == "__main__": + uvicorn.run("main:app", port=8098, reload=False)