import random import uvicorn from fastapi import FastAPI 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() if i > 0 else w for i, w in enumerate(p)]) + 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)