|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +import re |
| 4 | + |
3 | 5 | import fastapi |
| 6 | +from sqlalchemy.exc import IntegrityError |
4 | 7 |
|
| 8 | +from app.core.database import db |
| 9 | +from app.crud.dictionary import ( |
| 10 | + create_dictionary, |
| 11 | + delete_dictionary, |
| 12 | + list_dictionaries, |
| 13 | + read_dictionary_by_id, |
| 14 | + read_dictionary_by_term, |
| 15 | + update_dictionary, |
| 16 | +) |
5 | 17 | from app.schemas.dictionary import ( |
| 18 | + DictionaryBulkRegisterRequest, |
| 19 | + DictionaryBulkRegisterResponse, |
| 20 | + DictionaryBulkRegisterResult, |
| 21 | + DictionaryBulkRegisterSkipped, |
| 22 | + DictionaryEntryListResponse, |
| 23 | + DictionaryEntryResponse, |
| 24 | + DictionaryEntryUpdateRequest, |
6 | 25 | DictionaryLookupBatchResponse, |
7 | 26 | DictionaryLookupRequest, |
8 | 27 | DictionaryLookupResponse, |
9 | 28 | ) |
10 | 29 | from app.services.dictionary import lookup_term_summary, lookup_terms_summaries |
| 30 | +from app.services.text_analysis import vectorize_pretokenized_words |
11 | 31 |
|
12 | 32 | router = fastapi.APIRouter() |
| 33 | +_TERM_SPLIT_RE = re.compile(r"[,\s、,]+") |
| 34 | + |
| 35 | + |
| 36 | +def _ensure_db_available() -> None: |
| 37 | + if not db.is_available: |
| 38 | + raise fastapi.HTTPException( |
| 39 | + status_code=503, |
| 40 | + detail="DATABASE_URL is not configured", |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +def _to_entry_response(entry) -> DictionaryEntryResponse: |
| 45 | + return DictionaryEntryResponse( |
| 46 | + id=entry.id, |
| 47 | + term=entry.term, |
| 48 | + description=entry.description, |
| 49 | + meaning_vector=entry.meaning_vector, |
| 50 | + created_at=entry.created_at, |
| 51 | + updated_at=entry.updated_at, |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +def _parse_raw_terms(raw_terms: str) -> list[str]: |
| 56 | + terms = [term.strip() for term in _TERM_SPLIT_RE.split(raw_terms) if term.strip()] |
| 57 | + unique_terms = list(dict.fromkeys(terms)) |
| 58 | + for term in unique_terms: |
| 59 | + if len(term) > 128: |
| 60 | + raise fastapi.HTTPException( |
| 61 | + status_code=422, |
| 62 | + detail="each term must be at most 128 characters", |
| 63 | + ) |
| 64 | + return unique_terms |
13 | 65 |
|
14 | 66 |
|
15 | 67 | # 辞書検索API本体。 |
@@ -37,3 +89,171 @@ def lookup( |
37 | 89 | # 単体検索時は従来フォーマットのレスポンスを返す。 |
38 | 90 | result = lookup_term_summary(term=body.term or "", context=body.context) |
39 | 91 | return DictionaryLookupResponse(**result) |
| 92 | + |
| 93 | + |
| 94 | +@router.get( |
| 95 | + "/entries", |
| 96 | + response_model=DictionaryEntryListResponse, |
| 97 | + summary="辞書エントリ一覧を取得する", |
| 98 | +) |
| 99 | +def list_entries( |
| 100 | + q: str | None = fastapi.Query(default=None, description="用語の部分一致検索"), |
| 101 | + limit: int = fastapi.Query(default=100, ge=1, le=200), |
| 102 | + offset: int = fastapi.Query(default=0, ge=0), |
| 103 | +) -> DictionaryEntryListResponse: |
| 104 | + _ensure_db_available() |
| 105 | + normalized_q = q.strip() if isinstance(q, str) and q.strip() else None |
| 106 | + rows, total = list_dictionaries(term_query=normalized_q, limit=limit, offset=offset) |
| 107 | + return DictionaryEntryListResponse( |
| 108 | + items=[_to_entry_response(row) for row in rows], |
| 109 | + total=total, |
| 110 | + limit=limit, |
| 111 | + offset=offset, |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +@router.patch( |
| 116 | + "/entries/{entry_id}", |
| 117 | + response_model=DictionaryEntryResponse, |
| 118 | + summary="辞書エントリを更新する", |
| 119 | +) |
| 120 | +def patch_entry( |
| 121 | + entry_id: int, |
| 122 | + body: DictionaryEntryUpdateRequest, |
| 123 | +) -> DictionaryEntryResponse: |
| 124 | + _ensure_db_available() |
| 125 | + current = read_dictionary_by_id(entry_id) |
| 126 | + if current is None: |
| 127 | + raise fastapi.HTTPException(status_code=404, detail="entry not found") |
| 128 | + |
| 129 | + meaning_vector: list[float] | None = None |
| 130 | + if body.term is not None and body.term != current.term: |
| 131 | + duplicate = read_dictionary_by_term(body.term) |
| 132 | + if duplicate is not None and duplicate.id != entry_id: |
| 133 | + raise fastapi.HTTPException( |
| 134 | + status_code=409, |
| 135 | + detail="term already exists", |
| 136 | + ) |
| 137 | + vectors = vectorize_pretokenized_words([(body.term,)]) |
| 138 | + meaning_vector = vectors[0] if vectors else [] |
| 139 | + |
| 140 | + updated = update_dictionary( |
| 141 | + id=entry_id, |
| 142 | + term=body.term, |
| 143 | + description=body.description, |
| 144 | + meaning_vector=meaning_vector, |
| 145 | + ) |
| 146 | + if updated is None: |
| 147 | + raise fastapi.HTTPException(status_code=404, detail="entry not found") |
| 148 | + return _to_entry_response(updated) |
| 149 | + |
| 150 | + |
| 151 | +@router.delete( |
| 152 | + "/entries/{entry_id}", |
| 153 | + status_code=204, |
| 154 | + summary="辞書エントリを削除する", |
| 155 | +) |
| 156 | +def remove_entry(entry_id: int) -> fastapi.Response: |
| 157 | + _ensure_db_available() |
| 158 | + deleted = delete_dictionary(entry_id) |
| 159 | + if not deleted: |
| 160 | + raise fastapi.HTTPException(status_code=404, detail="entry not found") |
| 161 | + return fastapi.Response(status_code=204) |
| 162 | + |
| 163 | + |
| 164 | +@router.post( |
| 165 | + "/entries/bulk", |
| 166 | + response_model=DictionaryBulkRegisterResponse, |
| 167 | + summary="用語を一括登録する", |
| 168 | + description=( |
| 169 | + "カンマまたは空白区切りの用語を受け取り、" |
| 170 | + "Gemini で説明文を生成して辞書DBに登録します。" |
| 171 | + ), |
| 172 | +) |
| 173 | +def bulk_register( |
| 174 | + body: DictionaryBulkRegisterRequest, |
| 175 | +) -> DictionaryBulkRegisterResponse: |
| 176 | + _ensure_db_available() |
| 177 | + terms = _parse_raw_terms(body.raw_terms) |
| 178 | + if not terms: |
| 179 | + raise fastapi.HTTPException(status_code=422, detail="no terms found") |
| 180 | + |
| 181 | + results: list[DictionaryBulkRegisterResult] = [] |
| 182 | + created_count = 0 |
| 183 | + skipped_count = 0 |
| 184 | + |
| 185 | + for term in terms: |
| 186 | + existing = read_dictionary_by_term(term) |
| 187 | + if existing is not None: |
| 188 | + skipped_count += 1 |
| 189 | + results.append( |
| 190 | + DictionaryBulkRegisterResult( |
| 191 | + term=term, |
| 192 | + status="skipped", |
| 193 | + skipped=DictionaryBulkRegisterSkipped( |
| 194 | + term=term, |
| 195 | + reason="already exists", |
| 196 | + ), |
| 197 | + ) |
| 198 | + ) |
| 199 | + continue |
| 200 | + |
| 201 | + try: |
| 202 | + llm_result = lookup_term_summary(term=term) |
| 203 | + except fastapi.HTTPException as exc: |
| 204 | + skipped_count += 1 |
| 205 | + results.append( |
| 206 | + DictionaryBulkRegisterResult( |
| 207 | + term=term, |
| 208 | + status="skipped", |
| 209 | + skipped=DictionaryBulkRegisterSkipped( |
| 210 | + term=term, |
| 211 | + reason=f"lookup failed ({exc.status_code})", |
| 212 | + ), |
| 213 | + ) |
| 214 | + ) |
| 215 | + continue |
| 216 | + |
| 217 | + vectors = vectorize_pretokenized_words([(term,)]) |
| 218 | + meaning_vector = vectors[0] if vectors else [] |
| 219 | + |
| 220 | + try: |
| 221 | + entry_id = create_dictionary( |
| 222 | + term=term, |
| 223 | + description=llm_result["summary"], |
| 224 | + meaning_vector=meaning_vector, |
| 225 | + ) |
| 226 | + created_entry = read_dictionary_by_id(entry_id) |
| 227 | + if created_entry is None: |
| 228 | + raise fastapi.HTTPException( |
| 229 | + status_code=500, |
| 230 | + detail="failed to load created entry", |
| 231 | + ) |
| 232 | + created_count += 1 |
| 233 | + results.append( |
| 234 | + DictionaryBulkRegisterResult( |
| 235 | + term=term, |
| 236 | + status="created", |
| 237 | + entry=_to_entry_response(created_entry), |
| 238 | + ) |
| 239 | + ) |
| 240 | + except IntegrityError: |
| 241 | + # 並列処理などで同時に同一語が作成された場合はスキップ扱いにする。 |
| 242 | + skipped_count += 1 |
| 243 | + results.append( |
| 244 | + DictionaryBulkRegisterResult( |
| 245 | + term=term, |
| 246 | + status="skipped", |
| 247 | + skipped=DictionaryBulkRegisterSkipped( |
| 248 | + term=term, |
| 249 | + reason="already exists", |
| 250 | + ), |
| 251 | + ) |
| 252 | + ) |
| 253 | + |
| 254 | + return DictionaryBulkRegisterResponse( |
| 255 | + requested_count=len(terms), |
| 256 | + created_count=created_count, |
| 257 | + skipped_count=skipped_count, |
| 258 | + results=results, |
| 259 | + ) |
0 commit comments