Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
374 lines (348 loc) · 18.2 KB
/
Copy pathbuild.py
File metadata and controls
374 lines (348 loc) · 18.2 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
"""Rebuild and validate the skincare ingredients dataset.
uv run scripts/build.py --source export.json # refresh data/ingredients.json from a dictionary export, then rebuild
uv run scripts/build.py # rebuild the CSVs, docs/ page and README stats from data/ingredients.json
uv run scripts/build.py --check # validate what is committed (CI): schema, CSV = JSON, page lists every ingredient
data/ingredients.json is the master file. Ingredient text comes from the Beauty Comparison ingredient dictionary;
the family flags are set by code rules (published names and patterns), never by hand.
"""
from __future__ import annotations
import argparse
import csv
import html
import io
import json
import re
import sys
from datetime import date
from pathlib import Path
from jsonschema import Draft202012Validator, FormatChecker
ROOT = Path(__file__).resolve().parent.parent
SITE = "https://beautycomparison.com"
PAGES = "https://behoss.github.io/skincare-ingredients/"
REPO = "https://github.com/behoss/skincare-ingredients"
AUDIT = "https://github.com/behoss/beauty-label-audit-2026"
JSON_OUT = ROOT / "data" / "ingredients.json"
CSV_OUT = ROOT / "data" / "ingredients.csv"
FAM_CSV = ROOT / "data" / "families.csv"
HTML_OUT = ROOT / "docs" / "index.html"
SCHEMA = ROOT / "schema" / "ingredients.schema.json"
README = ROOT / "README.md"
def from_export(src: dict) -> dict:
return {
"name": "Skincare ingredients decoded",
"updated": date.today().isoformat(),
"licence": "CC-BY-4.0",
"url": PAGES,
"families": [
{
"id": f["id"],
"label": f["label"],
"free_from_label": f["freeLabel"],
"what": f["short"],
"why_it_matters": f["why"],
}
for f in src["families"]
],
"ingredients": [
{
"slug": i["slug"],
"inci_name": i["name"].strip(),
"also_known_as": [a.strip() for a in i["aka"] if a.strip()],
"what_it_is": i["what"].strip(),
"what_it_does": [d.strip() for d in i["does"] if d.strip()],
"good_for": i["goodFor"].strip(),
"watch_out": i["watchOut"].strip(),
"flags": i["families"],
"key_active": i["actives"][0] if i["actives"] else None,
"url": f"{SITE}/ingredients/{i['slug']}",
}
for i in sorted(src["ingredients"], key=lambda i: i["name"].lower())
],
}
def family_ids(data: dict) -> list[str]:
return [f["id"] for f in data["families"]]
def to_csv(data: dict) -> str:
fams = family_ids(data)
buf = io.StringIO()
w = csv.writer(buf, lineterminator="\n")
w.writerow(
["slug", "inci_name", "also_known_as", "what_it_is", "what_it_does", "good_for", "watch_out", "flags", "key_active"]
+ [f"is_{f.replace('-', '_')}" for f in fams]
+ ["url"]
)
for i in data["ingredients"]:
w.writerow(
[
i["slug"],
i["inci_name"],
"; ".join(i["also_known_as"]),
i["what_it_is"],
"; ".join(i["what_it_does"]),
i["good_for"],
i["watch_out"],
"; ".join(i["flags"]),
i["key_active"]["label"] if i["key_active"] else "",
]
+ ["true" if f in i["flags"] else "false" for f in fams]
+ [i["url"]]
)
return buf.getvalue()
def fam_csv(data: dict) -> str:
buf = io.StringIO()
w = csv.writer(buf, lineterminator="\n")
w.writerow(["id", "label", "free_from_label", "what", "why_it_matters"])
for f in data["families"]:
w.writerow([f["id"], f["label"], f["free_from_label"], f["what"], f["why_it_matters"]])
return buf.getvalue()
def stats(data: dict) -> dict:
ing = data["ingredients"]
return {
"ingredients": len(ing),
"names": len(ing) + sum(len(i["also_known_as"]) for i in ing),
"flagged": sum(1 for i in ing if i["flags"]),
"actives": sum(1 for i in ing if i["key_active"]),
"families": len(data["families"]),
}
def page(data: dict) -> str:
s = stats(data)
e = html.escape
label = {f["id"]: f["label"] for f in data["families"]}
rows = []
for i in data["ingredients"]:
aka = f'<div class="aka">Also: {e(", ".join(i["also_known_as"]))}</div>' if i["also_known_as"] else ""
tags = "".join(f'<span class="tag">{e(label[f])}</span>' for f in i["flags"])
if i["key_active"]:
tags += f'<span class="tag act">{e(i["key_active"]["label"])}</span>'
does = f'<div class="does">{e("; ".join(i["what_it_does"]))}</div>' if i["what_it_does"] else ""
rows.append(
f'<tr id="{i["slug"]}" data-f="{" ".join(i["flags"])}{" active" if i["key_active"] else ""}">'
f'<td><a href="{e(i["url"])}">{e(i["inci_name"])}</a>{aka}</td>'
f"<td>{e(i['what_it_is'])}{does}</td><td>{tags}</td></tr>"
)
fam_cards = "".join(
f'<li><b>{e(f["label"])}</b> <span class="free">{e(f["free_from_label"])}</span><p>{e(f["what"])} {e(f["why_it_matters"])}</p></li>'
for f in data["families"]
)
options = "".join(f'<option value="{f["id"]}">{e(f["label"])}</option>' for f in data["families"])
ld = {
"@context": "https://schema.org",
"@type": "Dataset",
"name": "Skincare ingredients decoded: INCI names in plain English",
"description": (
f"{s['ingredients']} cosmetic ingredient (INCI) names explained in plain English: what each one is, what it does "
"in a formula, who it suits, who should be careful, and free-from flags for fragrance, essential oils, "
"fragrance allergens, drying alcohol, sulfates, silicones, parabens and more. JSON and CSV, free to reuse."
),
"url": PAGES,
"sameAs": REPO,
"keywords": [
"INCI",
"cosmetic ingredients",
"skincare ingredients",
"fragrance-free",
"ingredient dictionary",
"open data",
],
"creator": {"@type": "Person", "name": "Bez", "url": "https://behoss.github.io"},
"license": "https://creativecommons.org/licenses/by/4.0/",
"isAccessibleForFree": True,
"dateModified": data["updated"],
"isBasedOn": f"{SITE}/ingredients",
"distribution": [
{"@type": "DataDownload", "encodingFormat": "application/json", "contentUrl": f"{PAGES}ingredients.json"},
{"@type": "DataDownload", "encodingFormat": "text/csv", "contentUrl": f"{PAGES}ingredients.csv"},
],
}
title = f"Skincare ingredients decoded: {s['ingredients']} INCI names in plain English"
desc = (
f"What {s['ingredients']} cosmetic ingredients are and what they do, in plain English, with free-from flags "
"for fragrance, essential oils, allergens, alcohol and more. Free open data in CSV and JSON."
)
return f"""<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{e(title)}</title>
<meta name="description" content="{e(desc)}">
<link rel="canonical" href="{PAGES}">
<meta name="color-scheme" content="light">
<meta property="og:title" content="{e(title)}">
<meta property="og:description" content="{e(desc)}">
<meta property="og:url" content="{PAGES}">
<meta property="og:type" content="website">
<script type="application/ld+json">{json.dumps(ld, ensure_ascii=False)}</script>
<style>
:root{{--ink:#1c1917;--mute:#57534e;--line:#e7e5e4;--bg:#fafaf9;--brand:#be185d;--brand2:#9d174d;--soft:#fce7f3}}
*{{box-sizing:border-box}}html{{color-scheme:light}}
body{{margin:0;font:16px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;color:var(--ink);background:#fff}}
.w{{max-width:1200px;margin:0 auto;padding:0 20px}}
header{{background:linear-gradient(180deg,#fdf2f8,#fff);border-bottom:1px solid var(--line)}}
.top{{display:flex;justify-content:space-between;align-items:center;padding:16px 0;font-size:15px}}
.top a{{color:var(--mute);text-decoration:none}}.top a:hover{{color:var(--brand)}}
.hero{{padding:28px 0 36px}}
h1{{font-size:clamp(28px,4.4vw,46px);line-height:1.12;margin:0 0 14px;letter-spacing:-.02em}}
.lead{{font-size:19px;color:var(--mute);max-width:780px;margin:0 0 22px}}
.stats{{display:flex;flex-wrap:wrap;gap:12px;margin:0 0 24px;padding:0;list-style:none}}
.stats li{{background:#fff;border:1px solid var(--line);border-radius:12px;padding:12px 16px;min-width:150px}}
.stats b{{display:block;font-size:26px;line-height:1.1}}
.stats span{{color:var(--mute);font-size:14px}}
.cta{{display:flex;flex-wrap:wrap;gap:12px;align-items:center}}
.btn{{display:inline-block;background:var(--brand);color:#fff;text-decoration:none;font-weight:600;padding:13px 22px;border-radius:10px}}
.btn:hover{{background:var(--brand2)}}
.btn2{{display:inline-block;color:var(--brand);border:1px solid var(--brand);text-decoration:none;font-weight:600;padding:12px 20px;border-radius:10px}}
.btn2:hover{{background:var(--soft)}}
main{{padding:28px 0 40px}}
.bar{{display:flex;flex-wrap:wrap;gap:12px;align-items:center;margin-bottom:14px}}
input[type=search],select{{font:inherit;padding:12px 14px;border:1px solid #d6d3d1;border-radius:10px;background:#fff}}
input[type=search]{{flex:1 1 280px}}
input[type=search]:focus,select:focus{{outline:2px solid var(--brand);border-color:var(--brand)}}
#n{{color:var(--mute);font-size:14px}}
table{{width:100%;border-collapse:collapse;font-size:15px}}
th{{text-align:left;font-size:13px;text-transform:uppercase;letter-spacing:.04em;color:var(--mute);border-bottom:2px solid var(--line);padding:10px 8px}}
td{{border-bottom:1px solid var(--line);padding:10px 8px;vertical-align:top}}
td:first-child{{width:24%}} td:last-child{{width:20%}}
tr:hover td{{background:var(--bg)}}
td a{{color:var(--brand);font-weight:600;word-break:break-word}}
.aka,.does{{color:var(--mute);font-size:13px;margin-top:3px}}
.tag{{display:inline-block;font-size:12px;font-weight:600;background:#fff7ed;color:#9a3412;border:1px solid #fed7aa;border-radius:999px;padding:2px 8px;margin:0 4px 4px 0}}
.tag.act{{background:#ecfdf5;color:#065f46;border-color:#a7f3d0}}
section.fam{{padding:8px 0 32px}}
section.fam h2,section.about h2{{font-size:22px;margin:0 0 12px}}
.grid{{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:12px;padding:0;margin:0;list-style:none}}
.grid li{{border:1px solid var(--line);border-radius:12px;padding:14px 16px;background:#fff}}
.grid p{{margin:6px 0 0;color:var(--mute);font-size:14px}}
.free{{font-size:12px;color:var(--brand2);background:var(--soft);border-radius:999px;padding:2px 8px;margin-left:4px}}
section.about{{background:var(--bg);border-top:1px solid var(--line);padding:32px 0}}
section.about p,section.about li{{color:#44403c;max-width:820px}}
section.about a{{color:var(--brand)}}
code{{font:14px ui-monospace,SFMono-Regular,Menlo,monospace;background:#fff;border:1px solid var(--line);border-radius:5px;padding:1px 5px}}
footer{{padding:22px 0;color:var(--mute);font-size:14px;border-top:1px solid var(--line)}}
footer a{{color:var(--mute)}}
@media (max-width:640px){{
.lead{{font-size:17px}} .stats li{{min-width:calc(50% - 6px);flex:1}} .stats b{{font-size:21px;white-space:nowrap}} .top{{font-size:14px;gap:12px}} .top span{{white-space:nowrap}} select{{flex:1 1 100%}}
thead{{display:none}} table,tbody,tr,td{{display:block;width:100%!important}}
tr{{border-bottom:1px solid var(--line);padding:10px 0}} td{{border:0;padding:3px 0}}
}}
</style>
</head>
<body>
<header>
<div class="w">
<nav class="top"><strong>Skincare ingredients data</strong><span><a href="{REPO}">GitHub</a> · <a href="{SITE}">Beauty Comparison</a></span></nav>
<div class="hero">
<h1>Skincare ingredients decoded, in plain English</h1>
<p class="lead">What {s["ingredients"]} cosmetic ingredients really are, what they do in a formula, who they suit and who should be careful. Every name is flagged for fragrance, essential oils, fragrance allergens, drying alcohol, sulfates, silicones and more.</p>
<ul class="stats">
<li><b>{s["ingredients"]}</b><span>ingredients explained</span></li>
<li><b>{s["names"]:,}</b><span>names and synonyms</span></li>
<li><b>{s["families"]}</b><span>free-from families</span></li>
<li><b>{data["updated"]}</b><span>last updated</span></li>
</ul>
<div class="cta">
<a class="btn" href="{SITE}">Compare beauty products by what is really inside</a>
<a class="btn2" href="{SITE}/tools/ingredient-checker">Check any ingredient list</a>
<a class="btn2" href="ingredients.csv">Download CSV</a>
<a class="btn2" href="ingredients.json">Download JSON</a>
</div>
</div>
</div>
</header>
<main class="w">
<div class="bar">
<input type="search" id="q" placeholder="Search an ingredient, e.g. niacinamide, parfum, limonene" aria-label="Search ingredients">
<select id="fam" aria-label="Filter by family"><option value="">All ingredients</option><option value="active">Key actives</option>{options}</select>
<span id="n">{s["ingredients"]} ingredients</span>
</div>
<table>
<thead><tr><th>Ingredient (INCI)</th><th>What it is and does</th><th>Flags</th></tr></thead>
<tbody id="rows">
{chr(10).join(rows)}
</tbody>
</table>
</main>
<section class="fam">
<div class="w">
<h2>The {s["families"]} free-from families</h2>
<ul class="grid">{fam_cards}</ul>
</div>
</section>
<section class="about">
<div class="w">
<h2>About this data</h2>
<p>Each ingredient links to its full page on <a href="{SITE}/ingredients">Beauty Comparison's ingredient dictionary</a>, with the longer explanation, common questions and the products that list it. To see which of these ingredients a real product contains, paste its label into the free <a href="{SITE}/tools/ingredient-checker">ingredient checker</a>.</p>
<ul>
<li><b>Files:</b> <a href="ingredients.json">ingredients.json</a>, <a href="ingredients.csv">ingredients.csv</a> (one row per ingredient, a true/false column per family) and <a href="families.csv">families.csv</a>.</li>
<li><b>Flags</b> come from code rules applied to the INCI name, so the same name always gets the same flags.</li>
<li><b>Sister dataset:</b> <a href="{AUDIT}">Beauty label audit 2026</a>, 1,641 real product ingredient lists decoded against the same 12 families.</li>
<li><b>Licence:</b> data under <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>; credit "Skincare ingredient data by Bez, <a href="{SITE}">Beauty Comparison</a>". Code under MIT. Source: <a href="{REPO}">github.com/behoss/skincare-ingredients</a>.</li>
</ul>
</div>
</section>
<footer><div class="w">Skincare ingredient data by <a href="https://behoss.github.io">Bez</a> · updated {data["updated"]} · <a href="{SITE}">Beauty Comparison</a></div></footer>
<script>
(function(){{var q=document.getElementById('q'),s=document.getElementById('fam'),n=document.getElementById('n'),rs=[].slice.call(document.querySelectorAll('#rows tr'));
var tx=rs.map(function(r){{return r.textContent.toLowerCase()}});
function f(){{var v=q.value.trim().toLowerCase(),o=s.value,k=0;rs.forEach(function(r,i){{var m=(!v||tx[i].indexOf(v)>-1)&&(!o||(' '+r.dataset.f+' ').indexOf(' '+o+' ')>-1);r.hidden=!m;if(m)k++}});n.textContent=k+(k===1?' ingredient':' ingredients')}}
q.addEventListener('input',f);s.addEventListener('change',f)}})();
</script>
</body>
</html>
"""
def validate(data: dict, csv_text: str, fam_text: str, page_text: str) -> list[str]:
errs = [
f"{'/'.join(map(str, e.path))}: {e.message}"
for e in Draft202012Validator(json.loads(SCHEMA.read_text()), format_checker=FormatChecker()).iter_errors(data)
]
if errs:
return errs
slugs = [i["slug"] for i in data["ingredients"]]
if len(slugs) != len(set(slugs)):
errs.append("duplicate slugs")
if csv_text != to_csv(data) or fam_text != fam_csv(data):
errs.append("data/*.csv does not match data/ingredients.json (run scripts/build.py)")
for i in data["ingredients"]:
if f'<tr id="{i["slug"]}"' not in page_text:
errs.append(f"docs/index.html is missing {i['slug']}")
return errs
def write_readme(data: dict) -> None:
s = stats(data)
line = (
f"<!-- stats -->{s['ingredients']} ingredients explained, {s['names']:,} names and synonyms, "
f"{s['flagged']} flagged in a free-from family, {s['actives']} key actives. Last updated: {data['updated']}.<!-- /stats -->"
)
README.write_text(re.sub(r"<!-- stats -->.*?<!-- /stats -->", line, README.read_text(), flags=re.DOTALL))
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--check", action="store_true", help="validate the committed files only")
ap.add_argument("--source", help="dictionary export (JSON) to refresh data/ingredients.json from")
a = ap.parse_args()
docs = ROOT / "docs"
if a.check:
data = json.loads(JSON_OUT.read_text())
errs = validate(data, CSV_OUT.read_text(), FAM_CSV.read_text(), HTML_OUT.read_text())
for f in ("ingredients.json", "ingredients.csv", "families.csv"):
if (docs / f).read_text() != (ROOT / "data" / f).read_text():
errs.append(f"docs/{f} differs from data/{f} (run scripts/build.py)")
else:
data = from_export(json.loads(Path(a.source).read_text())) if a.source else json.loads(JSON_OUT.read_text())
csv_text, fam_text, page_text = to_csv(data), fam_csv(data), page(data)
errs = validate(data, csv_text, fam_text, page_text)
if not errs:
json_text = json.dumps(data, ensure_ascii=False, indent=1) + "\n"
for d in (ROOT / "data", docs):
(d / "ingredients.json").write_text(json_text)
(d / "ingredients.csv").write_text(csv_text)
(d / "families.csv").write_text(fam_text)
HTML_OUT.write_text(page_text)
write_readme(data)
if errs:
print(f"FAIL: {len(errs)} problem(s)", *errs[:20], sep="\n ")
return 1
s = stats(data)
print(
f"OK: {s['ingredients']} ingredients, {s['names']} names, {s['flagged']} flagged, {s['actives']} actives, updated {data['updated']}"
)
return 0
if __name__ == "__main__":
sys.exit(main())