File size: 5,409 Bytes
e2bb8e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e83297
 
 
e2bb8e8
3e83297
e2bb8e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e83297
e2bb8e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fe8a75
 
 
e2bb8e8
 
 
7fe8a75
 
 
 
 
 
 
 
 
e2bb8e8
 
7fe8a75
 
 
 
e2bb8e8
7fe8a75
e2bb8e8
 
 
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
"""Turn an approved submission into a src/data/*.js entry + a text splice.

The site's data files (src/data/organizations.js, models.js, datasets.js,
blogs.js) are hand-formatted flat JS arrays, not JSON — see the real
examples this module's tests are based on. Rather than parsing/rewriting
the whole file as an AST, we do a plain text insertion, since the existing
formatting is simple and consistent: 2-space indent for `{`/`}`, 4-space
indent for fields, `description`/`excerpt` always on their own line.
"""

import json

# Canonical tag list — mirrors src/data/themes.js themeIds.
VALID_TAGS = [
    "biology", "chemistry", "physics", "medicine", "mathematics",
    "engineering", "earth-science", "astronomy", "genomics",
    "biotechnology", "materials-science", "climate", "energy",
    "ecology", "conservation", "benchmark", "scientific-reasoning",
]

# type -> (file path relative to repo root, exported array name, required fields)
TARGETS = {
    "organization": ("src/data/organizations.js", "organizations",
                      ["id", "name", "link", "tags"]),
    "model": ("src/data/models.js", "models",
              ["id", "slug", "name", "orgId", "type", "description", "tags"]),
    "dataset": ("src/data/datasets.js", "datasets",
                ["id", "slug", "orgId", "type", "description", "tags"]),
    # `slug` and `orgId` are legitimately absent for external (non-HF-blog)
    # and non-partnership posts — see e.g. the tamarind.bio entries in
    # blogs.js, most of which have slug: null and orgId: null.
    "blog": ("src/data/blogs.js", "blogs",
             ["id", "title", "date", "excerpt", "link", "tags"]),
}


def target_file(type_: str) -> str:
    return TARGETS[type_][0]


def missing_fields(type_: str, fields: dict) -> list[str]:
    _, _, required = TARGETS[type_]
    return [f for f in required if not fields.get(f)]


def _js_string(value) -> str:
    return json.dumps(value)


def render_entry(type_: str, fields: dict) -> str:
    """Render a single object literal matching the existing file style."""
    if type_ == "organization":
        lines = [
            "  {",
            f'    id: {_js_string(fields["id"])},',
            f'    name: {_js_string(fields["name"])},',
            f'    logo: getOrgLogo({_js_string(fields["id"])}),',
            "    description:",
            f'      {_js_string(fields.get("description", ""))},',
            f'    link: {_js_string(fields["link"])},',
            f'    tags: {json.dumps(fields["tags"])},',
            "  },",
        ]
    elif type_ == "model":
        lines = [
            "  {",
            f'    id: {_js_string(fields["id"])},',
            f'    slug: {_js_string(fields["slug"])},',
            f'    name: {_js_string(fields["name"])},',
            f'    orgId: {_js_string(fields["orgId"])},',
            f'    type: {_js_string(fields["type"])},',
            "    description:",
            f'      {_js_string(fields["description"])},',
            f'    tags: {json.dumps(fields["tags"])},',
            "  },",
        ]
    elif type_ == "dataset":
        lines = [
            "  {",
            f'    id: {_js_string(fields["id"])},',
            f'    slug: {_js_string(fields["slug"])},',
            f'    orgId: {_js_string(fields["orgId"])},',
            f'    type: {_js_string(fields["type"])},',
            "    description:",
            f'      {_js_string(fields["description"])},',
            f'    tags: {json.dumps(fields["tags"])},',
            "  },",
        ]
    elif type_ == "blog":
        lines = [
            "  {",
            f'    id: {_js_string(fields["id"])},',
            f'    title: {_js_string(fields["title"])},',
            f'    slug: {_js_string(fields["slug"]) if fields.get("slug") else "null"},',
            f'    orgId: {_js_string(fields["orgId"]) if fields.get("orgId") else "null"},',
            f'    date: {_js_string(fields["date"])},',
            "    excerpt:",
            f'      {_js_string(fields["excerpt"])},',
            f'    link: {_js_string(fields["link"])},',
            f'    tags: {json.dumps(fields["tags"])},',
            f'    featured: {"true" if fields.get("featured") else "false"},',
        ]
        if fields.get("upvotes") is not None:
            lines.append(f'    upvotes: {int(fields["upvotes"])},')
        lines.append("  },")
    else:
        raise ValueError(f"Unknown submission type: {type_}")

    return "\n".join(lines)


def insert_entry(file_content: str, type_: str, entry_block: str) -> str:
    """Insert entry_block at the end of the array, right before its closing
    `];` line."""
    _, array_name, _ = TARGETS[type_]
    lines = file_content.split("\n")
    opening = f"export const {array_name} = ["
    closing = "];"

    opening_at = None
    for i, line in enumerate(lines):
        if line.strip() == opening:
            opening_at = i
            break
    if opening_at is None:
        raise ValueError(f"Could not find `{opening}` in target file")

    insert_at = None
    for j in range(opening_at + 1, len(lines)):
        if lines[j].strip() == closing:
            insert_at = j
            break
    if insert_at is None:
        raise ValueError(f"Could not find closing `{closing}` for `{opening}` in target file")

    new_lines = lines[:insert_at] + entry_block.split("\n") + lines[insert_at:]
    return "\n".join(new_lines)