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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#!/usr/bin/python
import argparse
import functools
import json
import re
import shutil
from pathlib import Path
from typing import Any, Iterator, cast

import polars as pl

########
# main #
########


def main() -> None:
    args = read_args()

    data = read_data(
        args.related_subjects, args.grades_lower, args.grades_higher
    )
    done_print("Read data.")
    load_print("Adding possible documents...")
    data = add_possible_documents(data)
    done_print("Added possible documents.")

    load_print("Writing data...")
    path = write_data(data)
    done_print(
        f"Wrote data to {path.resolve().relative_to(Path('.').resolve())}."
    )
    done_print("Data creation complete.")


def read_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        "--related-subjects",
        default="",
        help="Path of the related subjects json file"
        + " (see data/related_subjects.json)."
        + " Leave empty to not use any related subjects.",
    )
    parser.add_argument(
        "--grades-lower",
        type=int,
        default=0,
        help="Number of grades lower than the minimum document grade for"
        + " which to consider it possible.",
    )
    parser.add_argument(
        "--grades-higher",
        type=int,
        default=0,
        help="Number of grades higher than the maximum document grade for"
        + " which to consider it possible.",
    )
    return parser.parse_args()


def read_data(
    related_subjects_file: str, grades_lower: int, grades_higher: int
) -> pl.DataFrame:
    path = Path(__file__).parent / ".." / "data"
    load_print("Reading questions...")
    questions = read_questions(path)
    done_print("Read questions.")
    load_print("Reading pages...")
    pages = read_pages(
        path, related_subjects_file, grades_lower, grades_higher
    )
    done_print("Read pages.")
    load_print("Combining pages and questions...")
    return combine_documents(questions, pages)


def combine_documents(
    questions: pl.DataFrame, pages: pl.DataFrame
) -> pl.DataFrame:
    # create hash of urls to quickly associate links to ids
    page_hashes = {
        hash(url): id_ for url, id_ in zip(pages["url"], pages["id"])
    }

    questions = (
        questions.with_columns(
            [
                # convert all page links to the page ids, making sure each
                # page can only appear once in the list
                pl.col("page_links").apply(
                    lambda list_: list(
                        {
                            id_
                            for url in list_
                            if (
                                id_ := page_hashes.get(
                                    hash(
                                        url.replace(
                                            "https://www.alloprof.qc.ca", ""
                                        )
                                    )
                                )
                            )
                            is not None
                        }
                    )
                ),
                # convert question links to its id
                pl.col("question_links").apply(
                    lambda list_: list(
                        {
                            id_
                            for x in list_
                            if (
                                id_ := x.replace(
                                    "https://www.alloprof.qc.ca/zonedentraide/discussion/",  # noqa
                                    "",
                                ).split("/")[0]
                            )
                            != "https:"
                        }
                    )
                ),
            ]
        )
        # combine page and question links in a single list of ids
        .with_columns(
            pl.col("page_links").arr.concat("question_links").alias("links")
        )
        .drop(["page_links", "question_links"])
        .with_columns(
            [
                # to identify which document is a question or a page
                pl.lit(True).alias("is_query"),
                # to be able to find the actual question on the website
                pl.col("id")
                .apply(
                    lambda x: f"https://www.alloprof.qc.ca/zonedentraide/discussion/{x}"  # noqa
                )
                .alias("url"),
            ]
        )
    )

    pages = (
        pages
        # add columns needed to concatenate to questions
        .with_columns(
            [
                pl.col("id")
                .apply(lambda _: [])
                .cast(pl.List(pl.Utf8))
                .alias("links"),
                pl.lit(False).alias("is_query"),
                pl.col("id")
                .apply(lambda _: [])
                .cast(pl.List(pl.Utf8))
                .alias("images"),
                pl.col("url").apply(
                    lambda x: f"https://www.alloprof.qc.ca{x}"
                ),
            ]
        )
        # have pages repeated for each grade and subject it's relevant for
        .explode("grade").explode("subject")
    )

    return (
        pl.concat([questions, pages], how="diagonal")
        .rename({"links": "relevant"})
        .with_columns(pl.col("relevant").apply(sorted))
    )


def add_possible_documents(data: pl.DataFrame) -> pl.DataFrame:
    # extract list of possible documents for each combination of subject,
    # grade and language
    data = data.with_columns(
        (
            pl.col("subject")
            + ","
            + pl.col("grade")
            + ","
            + pl.col("language")
        ).alias("categories")
    )
    possible = (
        data.select(["id", "categories"])
        .unique()
        .groupby("categories")
        .agg(pl.list("id"))
        .rename({"id": "possible"})
    )
    # add possible documents only to questions
    data = pl.concat(
        [
            data.filter(pl.col("is_query"))
            .join(possible, on="categories")
            .drop("categories"),
            data.filter(~pl.col("is_query")).with_columns(
                pl.col("id")
                .apply(lambda _: [])
                .cast(pl.List(pl.Utf8))
                .alias("possible")
            ),
        ],
        how="diagonal",
    )
    # concatenate all subjects and grades for each document so there is only
    # a single unique document per line
    return (
        # combine all grades for each id and subject
        data.groupby(["id", "subject"])
        .agg([pl.exclude("grade").first(), pl.list("grade")])
        # combine all subjects for each id
        .groupby("id")
        .agg([pl.exclude("subject").first(), pl.list("subject")])
        # remove duplicate grades
        .with_columns(pl.col("grade").arr.unique())
    )


def write_data(data: pl.DataFrame) -> Path:
    path = Path(__file__).parent / ".." / "data" / "alloprof.csv"
    data = data.with_columns(
        [
            pl.col("subject").arr.join(";"),
            pl.col("grade").arr.join(";"),
            pl.col("images").arr.join(";"),
            pl.col("relevant").arr.join(";"),
            pl.col("possible").arr.join(";"),
        ]
    )
    data.write_csv(path)
    return path


#############
# questions #
#############


def read_questions(path: Path) -> pl.DataFrame:
    path = path / "questions"
    questions = read_questions_(path)
    answers = read_answers(path)
    grades = read_grades(path)
    subjects = read_subjects(path)

    return (
        questions
        # convert subject and grade ids to their name
        .join(subjects, on="CategoryID")
        .drop("CategoryID")
        .join(grades, on="GradeID")
        .drop("GradeID")
        # add answers and extract links and images
        .join(answers, on="id", how="left")
        .pipe(extract_relevant_links)
        .with_columns(
            [
                pl.col("id").cast(pl.Utf8),  # to make it consistent with pages
                pl.col("text").apply(extract_text_from_json),
                pl.col("text").apply(extract_images_from_json).alias("images"),
            ]
        )
    )


def read_questions_(path: Path) -> pl.DataFrame:
    return pl.read_json(path / "discussions.json").select(
        [
            pl.col("DiscussionID").alias("id"),
            pl.col("Body").alias("text"),
            pl.col("Language").alias("language"),
            pl.col("InsertUserID").alias("user"),
            pl.col("CategoryID"),
            pl.col("GradeID"),
        ]
    )


def read_answers(path: Path) -> pl.DataFrame:
    return (
        pl.read_json(path / "comments.json")
        .filter(~pl.col("DateAccepted").is_null())
        .select(
            [
                pl.col("DiscussionID").alias("id"),
                pl.col("Body").alias("answer"),
            ]
        )
    )


def read_grades(path: Path) -> pl.DataFrame:
    return pl.read_json(path / "grades.json").select(
        [pl.col("GradeID"), pl.col("Name").alias("grade")]
    )


def read_subjects(path: Path) -> pl.DataFrame:

    return pl.read_json(path / "categories.json").select(
        [
            pl.col("CategoryID"),
            # convert french subjects to english to make them consistent with
            # pages
            pl.col("Name").apply(convert_subject).alias("subject"),
        ]
    )


def extract_relevant_links(data: pl.DataFrame) -> pl.DataFrame:
    def extract_links(text: str) -> list[str]:
        return list(
            set(
                re.findall(
                    r"(https?:(?:\\)?/(?:\\)?/[a-zA-Z0-9/\\\.-]+)",
                    text.replace("\\/", "/"),
                )
            )
        )

    def extract_page_links(links: list[str]) -> list[str]:
        return [link for link in links if "/eleves/bv/" in link]

    def extract_question_links(links: list[str]) -> list[str]:
        return [link for link in links if "/zonedentraide/discussion" in link]

    return (
        data.with_columns(pl.col("answer").fill_null(""))
        .with_columns(pl.col("answer").apply(extract_links).alias("links"))
        .with_columns(
            [
                pl.col("links").apply(extract_page_links).alias("page_links"),
                pl.col("links")
                .apply(extract_question_links)
                .alias("question_links"),
            ]
        )
    )


def extract_text_from_json(json_: str) -> str:

    try:
        return " ".join(list(extract_text(json.loads(json_))))
    except json.JSONDecodeError:
        return ""


def extract_text(raw_section: list[dict] | dict) -> Iterator[str]:
    if isinstance(raw_section, list):
        for section_content in raw_section:
            yield from extract_text(section_content)

    elif isinstance(raw_section, dict):
        for section_tag, section_content in raw_section.items():
            if section_tag == "insert" and isinstance(section_content, str):
                yield re.sub(r"\s+", " ", section_content.strip())
            elif section_tag == "url":
                yield section_content.strip()  # type: ignore
            else:
                yield from extract_text(section_content)


def extract_images_from_json(json_: str) -> list[str]:

    try:
        return list(extract_images(json.loads(json_)))
    except json.JSONDecodeError:
        return []


def extract_images(raw_section: list[dict] | dict) -> Iterator[str]:
    if isinstance(raw_section, list):
        for section_content in raw_section:
            yield from extract_images(section_content)

    elif isinstance(raw_section, dict):
        for section_tag, section_content in raw_section.items():
            if section_tag == "url":
                yield cast(str, section_content)
            else:
                yield from extract_images(section_content)


#########
# pages #
#########


def read_pages(
    path: Path,
    related_subjects_file: str,
    grades_lower: int,
    grades_higher: int,
) -> pl.DataFrame:
    grades = read_grades(path / "questions")
    fr_pages = pl.read_json(path / "pages" / "page-content-fr.json")["data"]
    en_pages = pl.read_json(path / "pages" / "page-content-en.json")["data"]
    return (
        pl.DataFrame(
            [parse_page_data(page) for page in [*fr_pages, *en_pages]]
        )
        .with_columns(
            pl.col("subject")
            .apply(convert_subject)
            .apply(lambda subject: [subject])
        )
        .filter(pl.col("url") != "")
        .pipe(
            functools.partial(
                convert_grades,
                grades=grades,
                grades_lower=grades_lower,
                grades_higher=grades_higher,
            )
        )
        .pipe(
            functools.partial(
                add_related_subjects,
                related_subjects_file=related_subjects_file,
            )
        )
        .pipe(extract_page_text)
    )


def parse_page_data(data: dict[str, Any]) -> dict[str, str | int | list[str]]:
    try:
        page = {
            "id": data["file"]["uuid"],
            "url": data["file"]["breadcrumbs"]["current"]["routerLink"],
            "language": data["file"]["lang"],
            "subject": data["file"]["topic"],
            "grade": data["file"]["levels"],
            "title": data["file"]["title"],
            "tags": data["file"]["tags"],
            "content": " ".join(
                d["attributes"]["content"]
                for d in data["file"]["metatags"]
                if d["attributes"]["content"]
            ),
        }
        return {**page, "id": f"{page['id']}-{page['language']}"}
    except TypeError:
        return {}


def convert_grades(
    data: pl.DataFrame,
    grades: pl.DataFrame,
    grades_lower: int,
    grades_higher: int,
) -> pl.DataFrame:
    return (
        # add grades lower and higher
        data.with_columns(
            pl.col("grade").apply(
                lambda grades_: (
                    list(
                        range(
                            max(min(grades_) - grades_lower, 1),
                            min(grades_),
                        )
                    )
                    + list(grades_)
                    + list(
                        range(
                            max(grades_) + 1,
                            min(max(grades_) + grades_higher, 12) + 1,
                        )
                    )
                )
                if grades_ is not None
                else []
            )
        )
        # convert grades to their name
        .with_columns(
            pl.col("grade").apply(
                lambda grades_: pl.DataFrame({"GradeID": grades_})
                .join(grades, on="GradeID", how="left")["grade"]
                .to_list()
            )
        )
    )


def add_related_subjects(
    data: pl.DataFrame, related_subjects_file: str
) -> pl.DataFrame:
    if related_subjects_file == "":
        return data
    else:
        with open(related_subjects_file) as f:
            related_subjects = json.load(f)
        return data.with_columns(
            pl.col("subject").apply(
                lambda subject: list(subject) + related_subjects[subject[0]]
            )
        )


def extract_page_text(data: pl.DataFrame) -> pl.DataFrame:
    return data.with_columns(
        (
            pl.col("title")
            + " "
            + pl.col("tags").arr.join(" ")
            + " "
            + pl.col("content")
        ).alias("text")
    ).drop(["title", "tags", "content"])


#########
# utils #
#########


def load_print(text: str, symbol: str = "*") -> None:
    symbol = f"\033[1m[{symbol}]\033[0m"
    print(
        f"\r{symbol} {text}".ljust(shutil.get_terminal_size().columns),
        end="\r",
    )


def done_print(text: str, symbol: str = "+") -> None:
    symbol = f"\033[1m\033[92m[{symbol}]\033[0m"
    print(f"\r{symbol} {text}".ljust(shutil.get_terminal_size().columns))


def convert_subject(subject: str) -> str:
    subject_conversions = {
        "chemistry": ["chimie"],
        "contemporary_world": ["monde contemporain", "contemporary world"],
        "english": ["anglais"],
        "financial_ed": ["éducation financière", "financial education"],
        "french": ["français"],
        "geography": ["géographie"],
        "history": ["histoire"],
        "math": ["mathématiques", "mathematics"],
        "other": ["autre"],
        "physics": ["physique"],
        "science": ["sciences"],
    }
    match = [
        key
        for key, val in subject_conversions.items()
        if subject.lower() in [key, *val]
    ]
    if match:
        return match[0]
    else:
        return "other"


if __name__ == "__main__":
    main()