Skip to content

Commit 45c3f7b

Browse files
Reformating with Ruff
1 parent f6baa83 commit 45c3f7b

6 files changed

Lines changed: 125 additions & 126 deletions

File tree

main.py

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -34,45 +34,46 @@
3434
LABEL_CLEANUP_INTERVAL_SECONDS = int(os.environ.get("LABEL_CLEANUP_INTERVAL_SECONDS", 3600))
3535
_last_label_cleanup = 0.0
3636

37+
3738
@app.on_event("startup")
3839
async def startup():
3940
"""Initialize database resources required by the API."""
4041
WikidataLabel.initialize_database()
4142

43+
4244
@app.get(
4345
"/",
4446
responses={
4547
200: {
4648
"description": "Returns a list of relevant Wikidata property PIDs with similarity scores",
4749
"content": {
4850
"application/json": {
49-
"example": [{
50-
"Q42": "Douglas Adams (human), English writer, humorist, and dramatist...",
51-
}]
51+
"example": [
52+
{
53+
"Q42": "Douglas Adams (human), English writer, humorist, and dramatist...",
54+
}
55+
]
5256
}
5357
},
5458
},
5559
422: {
5660
"description": "Missing or invalid query parameter",
57-
"content": {
58-
"application/json": {
59-
"example": {"detail": "Invalid format specified"}
60-
}
61-
},
61+
"content": {"application/json": {"example": {"detail": "Invalid format specified"}}},
6262
},
6363
},
6464
)
6565
async def get_textified_wd(
66-
request: Request, background_tasks: BackgroundTasks,
66+
request: Request,
67+
background_tasks: BackgroundTasks,
6768
id: str = Query(..., examples="Q42,Q2"),
6869
pid: str = Query(None, examples="P31,P279"),
69-
lang: str = 'en',
70-
format: str = 'json',
70+
lang: str = "en",
71+
format: str = "json",
7172
external_ids: bool = True,
7273
references: bool = False,
7374
all_ranks: bool = False,
7475
qualifiers: bool = True,
75-
fallback_lang: str = 'en'
76+
fallback_lang: str = "en",
7677
):
7778
"""Retrieve Wikidata entities as structured JSON, natural text, or triplet lines.
7879
@@ -95,7 +96,7 @@ async def get_textified_wd(
9596
9697
**Returns:**
9798
98-
A dictionary keyed by requested entity ID (for example, `"Q42"`).
99+
A dictionary keyed by requested entity ID (for example, `"Q42"`).
99100
Each value depends on `format`:
100101
101102
- **json**: Structured entity payload with label, description, aliases, and claims.
@@ -105,9 +106,9 @@ async def get_textified_wd(
105106
try:
106107
filter_pids = []
107108
if pid:
108-
filter_pids = [p.strip() for p in pid.split(',')]
109+
filter_pids = [p.strip() for p in pid.split(",")]
109110

110-
qids = [q.strip() for q in id.split(',')]
111+
qids = [q.strip() for q in id.split(",")]
111112
label_factory = LazyLabelFactory(lang=lang, fallback_lang=fallback_lang)
112113

113114
entities = {}
@@ -158,7 +159,9 @@ async def get_textified_wd(
158159
fallback_lang=fallback_lang,
159160
label_factory=label_factory,
160161
debug=False,
161-
) if entity_data.get(qid) else None
162+
)
163+
if entity_data.get(qid)
164+
else None
162165
for qid in qids
163166
}
164167

@@ -168,8 +171,10 @@ async def get_textified_wd(
168171
all_ranks=all_ranks,
169172
references=references,
170173
filter_pids=filter_pids,
171-
qualifiers=qualifiers
172-
) if entity else None
174+
qualifiers=qualifiers,
175+
)
176+
if entity
177+
else None
173178
for qid, entity in entity_data.items()
174179
}
175180

@@ -179,9 +184,9 @@ async def get_textified_wd(
179184
return_data[qid] = None
180185
continue
181186

182-
if format == 'text':
187+
if format == "text":
183188
results = entity.to_text(lang)
184-
elif format == 'triplet':
189+
elif format == "triplet":
185190
results = entity.to_triplet()
186191
else:
187192
results = entity.to_json()

src/Normalizer/JSONNormalizer.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ def __init__(
4848
self.fallback_lang = fallback_lang
4949
self.debug = debug
5050

51-
5251
self.label_factory = label_factory or LazyLabelFactory(lang=lang, fallback_lang=fallback_lang)
5352

5453
# -------------------------------------------------------------------------
@@ -119,7 +118,7 @@ def normalize(
119118
external_ids=external_ids,
120119
include_references=references,
121120
all_ranks=all_ranks,
122-
qualifiers=qualifiers
121+
qualifiers=qualifiers,
123122
)
124123
if claim_obj is not None and claim_obj.values:
125124
claims_out.append(claim_obj)
@@ -171,7 +170,7 @@ def _build_claim(
171170
statement=st,
172171
datatype=datatype,
173172
include_references=include_references,
174-
qualifiers=qualifiers
173+
qualifiers=qualifiers,
175174
)
176175
if cv is not None:
177176
values.append(cv)

src/Normalizer/TTLNormalizer.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def normalize(
9494
references: bool = False,
9595
all_ranks: bool = False,
9696
qualifiers: bool = True,
97-
filter_pids: List[str] = []
97+
filter_pids: List[str] = [],
9898
) -> WikidataEntity:
9999
"""Normalize the parsed graph into a ``WikidataEntity`` tree.
100100
@@ -134,7 +134,7 @@ def normalize(
134134
include_references=references,
135135
all_ranks=all_ranks,
136136
qualifiers=qualifiers,
137-
filter_pids=filter_pids
137+
filter_pids=filter_pids,
138138
)
139139

140140
entity = WikidataEntity(
@@ -191,7 +191,7 @@ def _claims_for_subject(
191191
include_references: bool,
192192
all_ranks: bool,
193193
qualifiers: bool,
194-
filter_pids: List[str] = []
194+
filter_pids: List[str] = [],
195195
) -> Dict[str, List[Dict[str, Any]]]:
196196
"""Return mapping: pid -> list of statement dicts."""
197197
out: DefaultDict[str, List[Dict[str, Any]]] = defaultdict(list)
@@ -335,7 +335,7 @@ def _build_claim_object(
335335

336336
refs_obj: List[List[WikidataClaim]] = []
337337
if include_references:
338-
for ref in (st.get("references") or []):
338+
for ref in st.get("references") or []:
339339
ref_claims = [
340340
self._build_snak_claim(
341341
pid=rpid,

src/Textifier/WikidataTextifier.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
# Atomic value types
1616
# ---------------------------------------------------------------------------
1717

18+
1819
@dataclass(slots=True)
1920
class WikidataText:
2021
"""Object for Wikidata plain text values."""
@@ -124,6 +125,7 @@ def to_json(self) -> Any:
124125
# Core graph types
125126
# ---------------------------------------------------------------------------
126127

128+
127129
@dataclass(slots=True)
128130
class WikidataEntity:
129131
"""Object for Wikidata entities."""
@@ -138,11 +140,11 @@ def __bool__(self) -> bool:
138140
"""Return whether this entity has a usable id and label."""
139141
return bool(self.id) and self.label is not None and str(self.label) != ""
140142

141-
def to_text(self, lang='en', keep_empty: bool = False) -> str:
143+
def to_text(self, lang="en", keep_empty: bool = False) -> str:
142144
"""Render the entity into a readable text."""
143-
lang_var = LANGUAGE_VARIABLES.get(lang, LANGUAGE_VARIABLES.get('en'))
145+
lang_var = LANGUAGE_VARIABLES.get(lang, LANGUAGE_VARIABLES.get("en"))
144146

145-
label_str = str(self.label) if self.label else '<missing>'
147+
label_str = str(self.label) if self.label else "<missing>"
146148
string = label_str
147149

148150
if self.description:
@@ -206,12 +208,12 @@ def __bool__(self) -> bool:
206208
and any(bool(v) for v in self.values)
207209
)
208210

209-
def to_text(self, lang='en') -> str:
211+
def to_text(self, lang="en") -> str:
210212
"""Render the claim into a readable text."""
211-
lang_var = LANGUAGE_VARIABLES.get(lang, LANGUAGE_VARIABLES.get('en'))
213+
lang_var = LANGUAGE_VARIABLES.get(lang, LANGUAGE_VARIABLES.get("en"))
212214

213215
if self.values:
214-
values = lang_var[', '].join(v.to_text(lang) for v in self.values if v)
216+
values = lang_var[", "].join(v.to_text(lang) for v in self.values if v)
215217
return f"{str(self.property.label)}: {values}"
216218

217219
return f"{lang_var['has']} {str(self.property.label)}"
@@ -249,10 +251,9 @@ def to_triplet(self, as_qualifier: bool = False) -> str:
249251
@dataclass(slots=True)
250252
class WikidataClaimValue:
251253
"""Object for Wikidata claim values."""
254+
252255
claim: WikidataClaim
253-
value: Optional[
254-
Union[WikidataEntity, WikidataQuantity, WikidataTime, WikidataCoordinates, WikidataText]
255-
] = None
256+
value: Optional[Union[WikidataEntity, WikidataQuantity, WikidataTime, WikidataCoordinates, WikidataText]] = None
256257
qualifiers: List[WikidataClaim] = field(default_factory=list)
257258
references: List[List[WikidataClaim]] = field(default_factory=list)
258259
rank: Optional[str] = None # preferred|normal|deprecated
@@ -261,9 +262,9 @@ def __bool__(self) -> bool:
261262
"""Return whether this claim value has non-empty values."""
262263
return self.value is not None and str(self.value) != ""
263264

264-
def to_text(self, lang='en') -> str:
265+
def to_text(self, lang="en") -> str:
265266
"""Render the value and qualifiers as readable text."""
266-
lang_var = LANGUAGE_VARIABLES.get(lang, LANGUAGE_VARIABLES.get('en'))
267+
lang_var = LANGUAGE_VARIABLES.get(lang, LANGUAGE_VARIABLES.get("en"))
267268

268269
if not self:
269270
return ""

0 commit comments

Comments
 (0)