First version of parser and basic stats

This commit is contained in:
Johannes 2023-10-02 19:54:32 +02:00
parent ae544b567d
commit 0217bf4611
2 changed files with 74 additions and 0 deletions

16
main.py Normal file
View file

@ -0,0 +1,16 @@
#! /usr/bin/env python3
from datetime import datetime
from pathlib import Path
from parse import parse, wiki_stats
def print_wiki_stats(filename: str) -> None:
path = Path(filename)
timestamp = datetime.fromtimestamp(path.stat().st_ctime)
print(f"Stand: {timestamp.strftime('%d.%m.%Y %H:%m Uhr')}")
print(wiki_stats(*parse(path)))
if __name__ == "__main__":
print_wiki_stats("koma89_pretixdata.json")

58
parse.py Normal file
View file

@ -0,0 +1,58 @@
import json
from pathlib import Path
from typing import Dict, Tuple, Union # I have just python3.8 here :(
def parse(filename: Union[str, Path]) -> Tuple[
Dict[int, str],
Dict[int, int],
Dict[int, str],
Dict[int, Dict[Tuple[int, str], int]]
]:
"""Parse a JSON export from pretix.
:param filename: filename of the JSON export to parse.
:returns: Four mappings:
* item_id to item name
* item_id to order count of this item
* question_id to question identifier
* question_id to stats for this question, which identifies an answer by its item_id and actual answer.
The stats map this identifier to number of occurrences
"""
with open(filename, 'r', encoding='utf8') as f:
data = json.load(f)['event']
items = {i['id']: i['name'] for i in data['items']}
count_items = {id_: 0 for id_ in items}
questions = {q['id']: q['identifier'] for q in data['questions']}
quest_answers = {id_: {} for id_ in questions}
for order in data['orders']:
for position in order['positions']:
item_id = position['item']
count_items[item_id] += 1
for answer in position['answers']:
quest_id = answer['question']
answer_key = (item_id, answer['answer'])
quest_answers[quest_id][answer_key] = (
quest_answers[quest_id].get(answer_key, 0) + 1
)
return items, count_items, questions, quest_answers
def wiki_stats(items: Dict[int, str], count_items: Dict[int, int], questions: Dict[int, str],
quest_answers: Dict[int, Dict[Tuple[int, str], int]]) -> str:
"""Generate stats for the Wiki page.
Input parameters are output of the parse() function.
"""
ret = ""
ret += ('== Anmeldezahlen ==\n'
'{|class="wikitable sortable"\n'
'! Posten !! Anzahl\n'
'|-\n')
for item_id, item_name in items.items():
ret += f"|| {item_name} || {count_items.get(item_id)}\n|-\n"
ret += "|}\n"
return ret