Spaces:
Sleeping
Sleeping
File size: 7,816 Bytes
1ad4e76 54bac2e 02a9316 1ad4e76 54bac2e 8765030 54bac2e 8765030 1ad4e76 54bac2e 02a9316 54bac2e 02a9316 54bac2e 02a9316 8765030 02a9316 aae42e1 8765030 1ad4e76 8765030 1ad4e76 8765030 1ad4e76 8765030 1ad4e76 8765030 02a9316 1ad4e76 02a9316 54bac2e 02a9316 |
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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
from typing import List
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
import numpy as np
from pydantic import BaseModel, Field, conlist
from app.utils.embedding import get_embedding
app = FastAPI()
origins = [
"http://localhost:3000",
"http://localhost:8000",
"localhost:8000",
"https://your-space-name.hf.space",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Mount static files
app.mount(
"/static", StaticFiles(directory="app/build/static", html=True), name="static"
)
# Serve index.html at the root
@app.get("/")
def read_root():
return FileResponse("app/build/index.html")
words_db = []
@app.get("/api/words", tags=["words"])
async def get_words() -> dict:
return {"data": words_db}
@app.post("/api/add-word", tags=["words"])
async def add_word(word: dict) -> dict:
try:
word_embedding = get_embedding(word["item"])
words_db.append(word)
word["embedding"] = word_embedding.tolist()
return JSONResponse(
status_code=200,
content={"message": "Item created successfully", "success": True},
)
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/api/delete-word/{word_id}", tags=["words"])
async def delete_word(word_id: str) -> dict:
word_id = int(word_id)
for word in words_db:
if int(word["id"]) == word_id:
words_db.remove(word)
return {"data": {"Succesful"}}
return {"data": {"Word not found"}}
#### Category Words
common_category_words = []
@app.get("/api/common-category-words", tags=["category-words"])
async def get_common_category_words() -> dict:
return {"data": common_category_words}
@app.post("/api/add-common-category-words", tags=["category-words"])
async def add_common_category_words(new_word: dict) -> dict:
try:
for word in common_category_words:
if new_word["item"] == word["item"]:
raise HTTPException(status_code=400, detail="Word already exists")
word_embedding = get_embedding(new_word["item"])
new_word["embedding"] = word_embedding.tolist()
common_category_words.append(new_word)
return JSONResponse(
status_code=200,
content={"message": "Item created successfully", "success": True},
)
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/get-embedding", tags=["category-words"])
async def get_embedding_api() -> dict:
if len(common_category_words) > 1:
vectors = [word["embedding"] for word in common_category_words]
variances = np.var(vectors, axis=0)
low_variance_dims = np.argsort(variances)[:3]
result = {
"variances": variances.tolist(),
"top_variance_dims": low_variance_dims.tolist(),
}
return JSONResponse(status_code=200, content={"data": result, "success": True})
return JSONResponse(
status_code=200,
content={
"data": {"variances": [0] * 50, "top_variance_dims": [0, 1, 2]},
"message": "Not enough words for analysis",
"success": False,
},
)
@app.delete("/api/delete-common-category-words/{word_id}", tags=["category-words"])
async def delete_common_category_words(word_id: str) -> dict:
word_id = int(word_id)
for word in common_category_words:
if int(word["id"]) == word_id:
common_category_words.remove(word)
return {"data": {"Succesful"}}
return {"data": {"Word not found"}}
### Difference Semantic
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
class WordPair(BaseModel):
word1: str = Field(..., min_length=2)
word2: str = Field(..., min_length=2)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
errors = exc.errors()
detailed_messages = [f"Error in {err['loc'][1]}: {err['msg']}" for err in errors]
print(detailed_messages)
return JSONResponse(
status_code=HTTP_422_UNPROCESSABLE_ENTITY,
content={"detail": ", ".join(detailed_messages), "body": exc.body},
)
semantic_difference_db = {}
@app.get("/api/difference-semantic-words", tags=["difference-semantic"])
async def get_semantic_difference() -> dict:
return JSONResponse(
status_code=200, content={"data": semantic_difference_db, "success": True}
)
@app.post("/api/add-difference-semantic-words", tags=["difference-semantic"])
async def add_semantic_difference(new_words: WordPair):
try:
first_word = new_words.word1
second_word = new_words.word2
combined_word = f"{first_word}-{second_word}"
word_one_embedding = get_embedding(first_word)
word_two_embedding = get_embedding(second_word)
embedding = word_one_embedding - word_two_embedding
if (
combined_word in semantic_difference_db
or combined_word[::-1] in semantic_difference_db
):
raise HTTPException(
status_code=400, detail="Semantic difference already exists"
)
semantic_difference_db[combined_word] = {
"id": len(semantic_difference_db) + 1,
"word-1": first_word,
"word-2": second_word,
"embedding": embedding.tolist(),
}
return JSONResponse(
status_code=200,
content={"message": "Item created successfully", "success": True},
)
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/get-embedding-difference", tags=["difference-semantic"])
async def get_embedding_difference() -> dict:
try:
if len(semantic_difference_db) > 1:
vectors = [word["embedding"] for word in semantic_difference_db.values()]
variances = np.var(vectors, axis=0)
low_variance_dims = np.argsort(variances)[:3]
result = {
"variance": variances.tolist(),
"top_variance_dims": low_variance_dims.tolist(),
}
return JSONResponse(
status_code=200, content={"data": result, "success": True}
)
return JSONResponse(
status_code=200,
content={
"data": {"variance": [0] * 50, "top_variance_dims": [0, 1, 2]},
"message": "Not enough words for analysis",
"success": False,
},
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.delete(
"/api/delete-difference-semantic-words/{word_id}", tags=["difference-semantic"]
)
async def delete_semantic_difference(word_id: str) -> dict:
try:
word_id = int(word_id)
for word in semantic_difference_db.values():
if int(word["id"]) == word_id:
del semantic_difference_db[word["word-1"] + "-" + word["word-2"]]
return {"data": {"Succesful"}}
return JSONResponse(status_code=404, content={"data": {"Word not found"}})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
|