Skip to content

Commit 5ee53e3

Browse files
committed
code style
1 parent 7b66dad commit 5ee53e3

File tree

7 files changed

+38
-31
lines changed

7 files changed

+38
-31
lines changed

.env.example

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Docker Image Settings
22
IMAGE_NAME=uigf-api
33
CONTAINER_NAME=UIGF-API
4-
IMAGE_TAG=1.5
4+
IMAGE_TAG=2.0
55
EXTERNAL_PORT=3052
66

77
# App Settings

db/crud.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
import json
44
import redis
55
from db.models import I18nDict
6-
from typing import Dict, List, Optional
6+
from typing import Dict, Optional
77
from base_logger import logger
8-
from api_config import game_name_id_map, ACCEPTED_LANGUAGES, LANGUAGE_PAIRS
8+
from api_config import game_name_id_map
99

1010

1111
def get_game_id_by_name(this_game_name: str) -> Optional[int]:

db/models.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from .mysql_db import Base
2-
from sqlalchemy import Column, Integer, String, Date
2+
from sqlalchemy import Column, Integer, String
33

44
# ------------------------------------------------------------------------
55
# MODEL DECLARATIONS
@@ -31,4 +31,3 @@ class I18nDict(Base):
3131
ru_text = Column(String(255), default="")
3232
th_text = Column(String(255), default="")
3333
vi_text = Column(String(255), default="")
34-

db/mysql_db.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import os
21
from sqlalchemy import create_engine
32
from sqlalchemy.ext.declarative import declarative_base
43
from sqlalchemy.orm import sessionmaker
@@ -11,4 +10,4 @@
1110
engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
1211
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
1312
Base = declarative_base()
14-
logger.info(f"MySQL connection established to {DB_HOST}/{DB_NAME}")
13+
logger.info(f"MySQL connection established to {DB_HOST}/{DB_NAME}")

db/schemas.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
from pydantic import BaseModel
2-
from typing import Optional, Any
2+
from typing import Optional, Any, Literal
3+
from api_config import ACCEPTED_LANGUAGES
34

45

56
# ------------------------------------------------------------------------
67
# Pydantic Schemas for Requests/Responses
78
# ------------------------------------------------------------------------
89
class TranslateRequest(BaseModel):
9-
type: str
10-
lang: str
11-
game: str
10+
type: Literal["reverse", "normal"]
11+
lang: Literal[*ACCEPTED_LANGUAGES]
12+
game: Literal["genshin", "starrail", "zzz"]
1213
item_name: Optional[str] = None
1314
item_id: Optional[str] = None
1415

1516

1617
class TranslateResponse(BaseModel):
1718
item_id: Optional[Any] = None
18-
item_name: Optional[Any] = None
19+
item_name: Optional[Any] = None

main.py

+27-19
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
import os
22
import json
33
import hashlib
4-
from sqlalchemy import or_
5-
from typing import Optional, Dict
64
import redis
7-
from fastapi import FastAPI, HTTPException, BackgroundTasks, Request, Depends, Header
5+
import uvicorn
6+
from contextlib import asynccontextmanager
7+
from fastapi import FastAPI, HTTPException, BackgroundTasks, Request, Header
88
from fastapi.responses import RedirectResponse, FileResponse
99
from fastapi.middleware.cors import CORSMiddleware
10-
from contextlib import asynccontextmanager
1110
from sqlalchemy.orm import Session
12-
import uvicorn
11+
from sqlalchemy import or_
12+
from typing import Optional, Dict
13+
1314
from fetcher import fetch_genshin_impact_update, fetch_zzz_update, fetch_starrail_update
1415
from api_config import game_name_id_map, DOCS_URL, ACCEPTED_LANGUAGES, LANGUAGE_PAIRS, TOKEN
1516
from base_logger import logger
@@ -73,6 +74,18 @@ async def root():
7374

7475
@app.post("/translate", response_model=TranslateResponse, tags=["translate"])
7576
async def translate(request_data: TranslateRequest, request: Request):
77+
"""
78+
Translate an item name to an item ID, or vice versa.
79+
80+
- **type**: "normal" or "reverse"
81+
- **lang**: Language code (e.g. "en", "zh-cn")
82+
- **game**: Game name (e.g. "genshin", "starrail")
83+
- **item_name**: The item name to translate
84+
- **item_id**: The item ID to translate
85+
86+
If **`normal`**, text -> item_id
87+
If **`reverse`**, item_id -> text
88+
"""
7689
db = request.app.state.mysql
7790
# Normalize language
7891
lang = request_data.lang.lower()
@@ -105,7 +118,7 @@ async def translate(request_data: TranslateRequest, request: Request):
105118
# It's a list of words
106119
word_list = json.loads(word)
107120
rows = (
108-
db.query(column_attr, getattr(type(column_attr.property.parent.class_), 'item_id'))
121+
db.query(column_attr, getattr(column_attr.property.parent.class_, 'item_id'))
109122
.filter_by(game_id=game_id)
110123
.filter(column_attr.in_(word_list))
111124
.all()
@@ -120,14 +133,14 @@ async def translate(request_data: TranslateRequest, request: Request):
120133
return TranslateResponse(item_id=result_list)
121134
else:
122135
row = (
123-
db.query(getattr(type(column_attr.property.parent.class_), 'item_id'))
136+
db.query(getattr(column_attr.property.parent.class_, 'item_id'))
124137
.filter_by(game_id=game_id)
125138
.filter(column_attr == word)
126139
.first()
127140
)
128141
if not row:
129142
raise HTTPException(status_code=404, detail="Hash ID not found")
130-
return TranslateResponse(item_id=row[0])
143+
return TranslateResponse(item_id=row[0], item_name=word)
131144

132145
# ------------------------------------------------------------------
133146
# Translate "reverse": from item_id -> text
@@ -145,9 +158,9 @@ async def translate(request_data: TranslateRequest, request: Request):
145158
# It's a list
146159
item_id_list = json.loads(item_id)
147160
rows = (
148-
db.query(getattr(type(column_attr.property.parent.class_), 'item_id'), column_attr)
161+
db.query(getattr(column_attr.property.parent.class_, 'item_id'), column_attr)
149162
.filter_by(game_id=game_id)
150-
.filter(getattr(type(column_attr.property.parent.class_), 'item_id').in_(item_id_list))
163+
.filter(getattr(column_attr.property.parent.class_, 'item_id').in_(item_id_list))
151164
.all()
152165
)
153166
id_to_text_map = {r[0]: r[1] for r in rows}
@@ -161,18 +174,16 @@ async def translate(request_data: TranslateRequest, request: Request):
161174
)
162175
if not row:
163176
raise HTTPException(status_code=404, detail="Word at this ID not found")
164-
return TranslateResponse(item_name=row[0])
177+
return TranslateResponse(item_name=row[0], item_id=item_id)
165178

166179
else:
167180
raise HTTPException(status_code=403, detail="Translate type not supported")
168181

169182

170183
def build_language_filter(word: str):
171-
from sqlalchemy import or_
172-
from db.crud import ACCEPTED_LANGUAGES, get_lang_column
173184
or_conditions = []
174185
for lang_code in ACCEPTED_LANGUAGES:
175-
column_attr = get_lang_column(lang_code)
186+
column_attr = crud.get_lang_column(lang_code)
176187
or_conditions.append(column_attr == word)
177188
return or_(*or_conditions)
178189

@@ -346,6 +357,7 @@ def force_refresh_local_data(this_game_name: str, db: Session, redis_client: red
346357

347358
@app.get("/md5/{this_game_name}", tags=["checksum"])
348359
async def get_checksum(this_game_name: str, background_tasks: BackgroundTasks):
360+
349361
if this_game_name not in game_name_id_map:
350362
raise HTTPException(status_code=403, detail="Game name not accepted")
351363
try:
@@ -375,11 +387,7 @@ def make_checksum(this_game_name: str):
375387
]
376388
# If none exist, force refresh
377389
if len(file_list) == 0:
378-
force_refresh_local_data(g)
379-
file_list = [
380-
f for f in os.listdir(dict_path)
381-
if f.endswith(".json") and "md5" not in f
382-
]
390+
raise RuntimeError("No Json files found, forcing refresh.")
383391

384392
checksum_dict = {}
385393
for json_file in file_list:

requirements.txt

106 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)