Skip to content

Commit 4e79efd

Browse files
committed
feat: revise return dict to return class
1 parent 6ac1e08 commit 4e79efd

2 files changed

Lines changed: 33 additions & 32 deletions

File tree

api/accent_marker.py

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import logging
66
import string
7-
from typing import Any
7+
from typing import Any, cast
88

99
import httpx
1010
import jaconv
@@ -15,6 +15,7 @@
1515

1616
from api.dependencies import get_http_client
1717
from api.furigana_marker import (
18+
MultiWordResultObject,
1819
RequestBody,
1920
SingleWordResultObject,
2021
mark_furigana_service,
@@ -267,40 +268,41 @@ async def mark_accent(
267268
try:
268269
query_text = neologdn.normalize(request.text, tilde="normalize")
269270

270-
furigana_response = await mark_furigana_service(query_text, client)
271+
furigana_response = cast(
272+
Response, await mark_furigana_service(query_text, client)
273+
)
271274

272275
# 檢查 Yahoo 回傳
273-
if not furigana_response or "result" not in furigana_response:
276+
if furigana_response.status != 200 or not furigana_response.result:
274277
logger.warning(f"Yahoo Response Empty or Invalid: {furigana_response}")
275278

276-
furigana_results: list[dict[str, Any]] = furigana_response.get("result", [])
277-
logger.debug(f"Yahoo Results Count: {len(furigana_results)}")
279+
furigana_results = furigana_response.result or []
280+
logger.debug(f"Yahoo Results Count: {len(furigana_results or [])}")
278281

279282
ojad_surface, ojad_results = await get_ojad_result(query_text, client)
280283

281284
final_response_results = []
282285
ojad_idx_cnt = 0
283286

284-
logger.debug(f"🔍 [Type Check] furigana_results type: {type(furigana_results)}")
285287
logger.debug(
286-
"[Data Check] furigana_results sample (first item): "
288+
"🔍 [Data Check] First item:"
287289
f"{furigana_results[0] if furigana_results else 'Empty'}"
288290
)
289291

290292
for i, furigana_result in enumerate(furigana_results):
291-
logger.debug(f" 🔍 [Type Check] Item [{i}] type: {type(furigana_result)}")
292-
logger.debug(f" 🔍 [Data Check] Item keys: {furigana_result.keys()}")
293-
yahoo_furigana = furigana_result["furigana"]
293+
yahoo_furigana = furigana_result.furigana
294+
yahoo_surface = furigana_result.surface
295+
296+
is_multi_word = isinstance(furigana_result, MultiWordResultObject)
294297
yahoo_furigana_hira = jaconv.kata2hira(yahoo_furigana)
295-
yahoo_surface = furigana_result["surface"]
296298
accents: list[AccentInfo] = []
297299

298300
logger.debug(
299301
f"Processing Yahoo Word [{i}]: {yahoo_surface} ({yahoo_furigana})"
300302
)
301303

302304
# If query sub-text contains non-kana and non-kanji words, ignore it
303-
if "subword" not in furigana_result and any(
305+
if not is_multi_word and any(
304306
not is_kana_or_kanji(chr) for chr in yahoo_furigana
305307
):
306308
logger.debug(" -> Skipped (Not Kana/Kanji)")
@@ -382,16 +384,8 @@ async def mark_accent(
382384

383385
ojad_idx_cnt = temp_ojad_idx # Update global index
384386

385-
if "subword" not in furigana_result:
386-
final_response_results.append(
387-
SingleWordAccentResultObject(
388-
furigana=yahoo_furigana,
389-
surface=yahoo_surface,
390-
accent=accent_info_list,
391-
)
392-
)
393-
else:
394-
yahoo_subword: list[dict[str, str]] = furigana_result["subword"]
387+
if isinstance(furigana_result, MultiWordAccentResultObject):
388+
yahoo_subword = furigana_result.subword # ignore
395389
if len(yahoo_subword) > 0:
396390
logger.debug(
397391
"[Type Check] yahoo_subword element type: "
@@ -407,12 +401,20 @@ async def mark_accent(
407401
accent=accent_info_list,
408402
subword=[
409403
SingleWordResultObject(
410-
furigana=s["furigana"], surface=s["surface"]
404+
furigana=s.furigana, surface=s.surface
411405
)
412406
for s in yahoo_subword
413407
],
414408
)
415409
)
410+
else:
411+
final_response_results.append(
412+
SingleWordAccentResultObject(
413+
furigana=yahoo_furigana,
414+
surface=yahoo_surface,
415+
accent=accent_info_list,
416+
)
417+
)
416418
else:
417419
# [ERROR BLOCK]
418420
logger.error(

api/furigana_marker.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
"""
44

55
import os
6-
from typing import Any
76

87
import httpx
98
import yaml
@@ -82,8 +81,8 @@ class Response(BaseModel):
8281
async def mark_furigana_service(
8382
query_text: str,
8483
client: httpx.AsyncClient,
85-
) -> dict[str, Any]:
86-
"""Receive POST request, return a JSON response"""
84+
) -> Response:
85+
"""Receive POST request, return a Response object"""
8786

8887
# 輸入
8988
headers = {
@@ -106,14 +105,14 @@ async def mark_furigana_service(
106105
status=408,
107106
result=None,
108107
error=ErrorInfo(code=408, message="Yahoo API request timed out"),
109-
).model_dump()
108+
)
110109

111110
except httpx.HTTPError as e:
112111
return Response(
113112
status=500,
114113
result=None,
115114
error=ErrorInfo(code=500, message=f"HTTP error: {str(e)}"),
116-
).model_dump()
115+
)
117116

118117
if response.status_code != 200:
119118
return Response(
@@ -123,7 +122,7 @@ async def mark_furigana_service(
123122
code=response.status_code,
124123
message=f"Yahoo API request failed with status {response.status_code}",
125124
),
126-
).model_dump()
125+
)
127126

128127
result = response.json()
129128
if "result" not in result or "word" not in result["result"]:
@@ -133,7 +132,7 @@ async def mark_furigana_service(
133132
error=ErrorInfo(
134133
code=500, message="Unexpected response format from Yahoo API"
135134
),
136-
).model_dump()
135+
)
137136

138137
words = result["result"]["word"]
139138
parsed_result: list[SingleWordResultObject | MultiWordResultObject] = []
@@ -159,11 +158,11 @@ async def mark_furigana_service(
159158
)
160159
)
161160

162-
return Response(status=200, result=parsed_result).model_dump()
161+
return Response(status=200, result=parsed_result)
163162

164163

165164
async def mark_furigana(
166165
request: RequestBody,
167166
client: httpx.AsyncClient = Depends(get_http_client),
168-
) -> dict[str, Any]:
167+
) -> Response:
169168
return await mark_furigana_service(request.text, client)

0 commit comments

Comments
 (0)