aboutsummaryrefslogtreecommitdiffstats
path: root/generate_html_cs.py
blob: 519a2a0b5fa1358da2d88f9e52cdc0d2ecb126dd (plain) (blame)
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
#!/usr/bin/python3
import codecs
import logging
import re
import sys
from typing import Any, Dict

import jinja2

import xml.etree.ElementTree as et


logging.basicConfig(
    format="%(levelname)s:%(funcName)s:%(message)s", level=logging.DEBUG
)

cur_year = 2024

book_abbrs = {
    "Gn": "Gen",
    "Ex": "Exod",
    "Lv": "Lev",  # NA in source code,
    "Nu": "Num",
    "Dt": "Deut",
    "Jos": "Josh",
    "Jdc": "Judg",
    "Rth": "Ruth",
    "1Sm": "1%20Sam",
    "2Sm": "2%20Sam",
    "1Rg": "1%20Kgs",
    "2Rg": "2%20Kgs",
    "1Chr": "1%20Chr",
    "2Chr": "2%20Chr",
    "Esr": "Ezra",
    "Neh": "Neh",
    "Esth": "Esth",  # NA in source code,
    "Job": "Job",
    "Ps": "Ps",
    "Prv": "Prov",
    "Eccl": "Eccl",
    "Song": "Song",  # NA in source code,
    "Is": "Isa",
    "Jr": "Jer",
    "Thr": "Lam",
    "Ez": "Ezek",
    "Dn": "Dan",
    "Hos": "Hos",
    "Joel": "Joel",
    "Am": "Amos",
    "Obad": "Obad",  # NA in source code
    "Jon": "Jonah",
    "Mch": "Mic",
    "Nah": "Nah",  # NA in source code
    "Hab": "Hab",
    "Zph": "Zeph",
    "Hgg": "Hag",
    "Zch": "Zech",
    "Ml": "Mal",
    "Mt": "Matt",
    "Mc": "Mark",
    "L": "Luke",
    "J": "John",
    "Act": "Acts",
    "R": "Rom",
    "1K": "1%20Cor",
    "2K": "2%20Cor",
    "G": "Gal",
    "E": "Eph",
    "Ph": "Phil",
    "Kol": "Col",
    "1Th": "1%20Thess",
    "2Th": "2%20Thess",
    "1T": "1%20Tim",
    "2T": "2%20Tim",
    "Tt": "Titus",
    "Phm": "Phlm",
    "H": "Heb",
    "Jc": "Jas",
    "1P": "1%20Pet",
    "2P": "2%20Pet",
    "1J": "1%20John",
    "2J": "2%20John",
    "3J": "3%20John",
    "Jd": "Jude",
    "Ap": "Rev",
}

# https://wiki.crosswire.org/OSIS_Book_Abbreviations
OSIS_book_names = {
  "1.Mojžíšova": "Gen",
  "2.Mojžíšova": "Exod",
  "3.Mojžíšova": "Lev",
  "4.Mojžíšova": "Num",
  "5.Mojžíšova": "Deut",
  "Jozue": "Josh",
  "Soudců": "Judg",
  "Rút": "Ruth",
  "1.Samuelova": "1Sam",
  "2.Samuelova": "2Sam",
  "1.Královská": "1Kgs",
  "2.Královská": "2Kgs",
  "1.Paralipomenon": "1Chr",
  "2.Paralipomenon": "2Chr",
  "Ezdráš": "Ezra",
  "Nehemiáš": "Neh",
  "Ester": "Esth",
  "Jób": "Job",
  "Žalm": "Ps",
  "Přísloví": "Prov",
  "Kazatel": "Eccl",
  "Píseň": "Song",
  "Izaiáš": "Isa",
  "Jeremiáš": "Jer",
  "Pláč": "Lam",
  "Ezechiel": "Ezek",
  "Daniel": "Dan",
  "Ozeáš": "Hos",
  "Joel": "Joel",
  "Amos": "Amos",
  "Abdijáš": "Obad",
  "Jonáš": "Jonah",
  "Micheáš": "Mic",
  "Nahum": "Nah",
  "Abakuk": "Hab",
  "Sofoniáš": "Zeph",
  "Aggeus": "Hag",
  "Zachariáš": "Zech",
  "Malachiáš": "Mal",
  "Matouš": "Matt",
  "Marek": "Mark",
  "Lukáš": "Luke",
  "Jan": "John",
  "Skutky": "Acts",
  "Římanům": "Rom",
  "1.Korintským": "1Cor",
  "2.Korintským": "2Cor",
  "Galatským": "Gal",
  "Efezským": "Eph",
  "Filipským": "Phil",
  "Koloským": "Col",
  "1.Tesalonickým": "1Thess",
  "2.Tesalonickým": "2Thess",
  "1.Timoteovi": "1Tim",
  "2.Timoteovi": "2Tim",
  "Titovi": "Titus",
  "Filemonovi": "Phlm",
  "Židům": "Heb",
  "Jakubova": "Jas",
  "1.Petrova": "1Pet",
  "2.Petrova": "2Pet",
  "1.Janova": "1John",
  "2.Janova": "2John",
  "3.Janova": "3John",
  "Judova": "Jude",
  "Zjevení": "Rev",
}


def csv2dict(filename):
    out_dict = {}
    split_re = re.compile(r"\s+")
    field_names = ["no", "test", "cs_abbr", "cs_name", "de_abbr", "de_name"]
    with codecs.open(filename, "rb", "utf8") as csvfile:
        for row in csvfile:
            line_dict = dict(zip(field_names, split_re.split(row)))
            out_dict[line_dict["cs_abbr"]] = line_dict
    logging.debug("out_dict:\n%s", out_dict)
    return out_dict

"""
{%- macro bible_url(ref, bib_mod) -%}
    http://www.crosswire.org/study/passagestudy.jsp?key={{ ref.book
    }}+{{ ref.chapter }}%3A{{ ref.verse }}&mod={{ bibMod }}
{%- endmacro -%}
{%- macro verses(word) -%}
<p>{{ word.text }}</p>
      <p class="reference">{% if word.int_ref_id -%}
          <a href="{{ bible_url(word.int_ref_id) }}">
              {{ word.ref }}
          </a>
          {%- else %}
              {{ word.ref }}
          {%- endif %}</p>{%- endmacro -%}

     <Ev><SL>Lukáš 4,16-21</SL></Ev>
     <Ep><SL>Jakubova 4,13-15</SL></Ep>
     <Pr><SL>Filipským 4,10-20</SL></Pr>
     <AT><SL>Jozue 1,1-9</SL></AT>
     <Bl><SL>Žalm 100</SL></Bl>
"""
def parse_biblical_reference(instr: str) -> Dict[str, Any]:
    return {
      "book": "",
      "chapter": 0,
      "verse": 0,
      "ref": ""
    }


def parse_verses(lines):
    """
    Having list of <L> elements, make the text out of them (with
    <BR> elements where necessary).
    """
    out = ""
    logging.debug("lines = %s", ",".join(
        [et.tostring(l, encoding='unicode') for l in lines]))
    logging.debug("lines = len %s", len(lines))
    if len(lines) > 0:
        out = lines[0].text
        if len(lines) > 1:
            for line in lines[1:]:
                logging.debug("lines = %s", lines)
                logging.debug("another line = %s", line.text)
                if line.text is not None:
                    out += "<br>\n" + line.text
    logging.debug("body = %s", out)
    return out


def parse_body(elem):
    """Parse one verse element
    Example could be (or NT instead of OT, or DAY):
      <OT>
       <S b="Ps" ch="91" v="9"/>
       <L>V Hospodinu je tvé útočiště.</L>
       <SL>Žalm 91,9</SL>
      </OT>
    """
    logging.debug('elem:%s', et.tostring(elem, encoding='unicode'))
    if len(list(elem)) == 0:
        return None

    wword = {"text": ""}
    source_elem = elem.find("S")
    logging.debug("S elem = %s", et.tostring(source_elem, encoding='unicode'))
    logging.debug("S elem = attrib %s", source_elem.attrib)

    # biblical reference (computer readable)
    wword["ref_id"] = {
        "book": source_elem.attrib["b"],
        "chapter": source_elem.attrib["ch"],
        "verse": source_elem.attrib["v"],
    }
    logging.debug("wword['ref_id'] = %s", wword["ref_id"])

    # biblical reference (compatible with the English Bible programs)
    try:
        wword["int_ref_id"] = wword["ref_id"].copy()
        wword["int_ref_id"]["book"] = book_abbrs[wword["ref_id"]["book"]]
        logging.debug("book = %s / %s", wword["ref_id"], wword["int_ref_id"])
    except KeyError:
        logging.error("book = %s", wword["ref_id"])
        raise

    # text of the verse
    wword["text"] = parse_verses(list(elem.iter("L")))

    # references
    ref = elem.find("SL")
    logging.debug("ref = %s", et.tostring(ref, encoding='unicode'))
    if ref is not None:
        logging.debug("ref.text = %s", ref.text)
        wword["ref"] = ref.text
    return wword


def parse_losung(elem):
    """
    Parse one losung. Example:
    <LOSUNG d="1" m="1">
     <TL>Pátek 1. ledna 2021</TL>
     <OT>
      <S b="Lv" ch="19" v="11"/>
      <L>Nebudete krást ani obelhávat a podvádět svého bližního.</L>
      <SL>3.Mojžíšova 19,11</SL>
     </OT>
     <NT>
      <S b="1P" ch="3" v="8"/>
      <L>Všichni buďte jedné mysli, soucitní, plní bratrské lásky,
      milosrdní a pokorní, neodplácejte zlým za zlé ani urážkou za
      urážku, naopak žehnejte; vždyť jste byli povoláni k tomu, abyste
      se stali dědici požehnání.</L>
      <SL>1.Petrova 3,8-9</SL>
     </NT>
     <Ev><SL>Lukáš 4,16-21</SL></Ev>
     <Ep><SL>Jakubova 4,13-15</SL></Ep>
     <Pr><SL>Filipským 4,10-20</SL></Pr>
     <AT><SL>Jozue 1,1-9</SL></AT>
     <Bl><SL>Žalm 100</SL></Bl>
    </LOSUNG>

    <LOSUNG d="2" m="1">
     <TL>Sobota 2. ledna 2021</TL>
     <OT>
      <S b="Neh" ch="8" v="8"/>
      <L>Četli z knihy Božího zákona po oddílech a vykládali smysl, aby
      lid rozuměl tomu, co četli.</L>
      <SL>Nehemiáš 8,8</SL>
     </OT>
     <NT>
      <S b="Act" ch="28" v="30"/>
      <L>Pavel zůstal celé dva roky v najatém bytě a přijímal všechny,
      kdo za ním přišli, zvěstoval Boží království a učil všemu o Pánu
      Ježíši Kristu bez bázně a bez překážek.</L>
      <SL>Skutky 28,30-31</SL>
     </NT>
     <SR><SL>Jozue 24,1-26</SL></SR>
     <CR><SL>Lukáš 3,1-6</SL></CR>
    </LOSUNG>
    """
    logging.debug("losung = %s\n", et.tostring(elem, encoding='unicode'))
    out = {}
    date_id = (
        cur_year,
        int(elem.attrib["m"]),
        int(elem.attrib["d"]),
    )
    out["date_id"] = "%4d-%02d-%02d" % (date_id)
    logging.debug("date_id = %s", out["date_id"])

    out["date_full"] = elem.find("TL").text
    out["watchwords"] = []

    for tst in ["OT", "NT"]:
        sect = elem.find(tst)
        out["watchwords"].append(parse_body(sect))

    out["readings"] = []
    for read in ["SR", "CR", "Ev", "Ep", "Pr", "AT", "Bl"]:
        sect = elem.find(read)
        if sect is not None:
            try:
                out["readings"].append(
                    "\n".join([el.text for el in sect.findall("SL")])
                )
            except AttributeError:
                logging.exception("Parsing heslo pro %s", sect)
    logging.debug("readings = %s", out['readings'])

    out["chronicles"] = []
    for chron in elem.findall("C"):
        out["chronicles"].append(
            "\n".join([line.text for line in chron.findall("L")])
        )

    return date_id, out


def parse_day(elem, whole_dict):
    """
    Parsse <DAY> element.

    Example:
       <DAY d="1" m="1" type="holiday" name="Nový Rok  ">
         <S b="Kol" ch="3" v="17"/>
         <L>Všechno, cokoli mluvíte nebo děláte,</L>
         <L>čiňte ve jménu Pána Ježíše a skrze něho děkujte Bohu Otci.</L>
         <SL>Koloským 3,17</SL>
       </DAY>

       <DAY d="17" m="2" type="sunday" name="Invocavit"
            meaning="Vzývati mne bude a vyslyším jej. Žalm 91,15" ord="7">
         <S b="1J" ch="3" v="8"/>
         <L>Proto se zjevil Syn Boží, aby zmařil činy ďáblovy.</L>
         <SL>1.Janova 3,8b</SL>
       </DAY>

       <DAY d="13" m="1" type="week" name="Alianční modlitební týden  ">
       </DAY>
    """
    date_id = (
        cur_year,
        int(elem.attrib["m"]),
        int(elem.attrib["d"]),
    )
    logging.debug("date_id = %s", date_id)
    out = whole_dict[date_id]

    if elem.attrib["type"] == "holiday":
        out["holy_name"] = elem.attrib["name"].strip()
        out["holy_text"] = parse_body(elem)
    elif elem.attrib["type"] == "sunday":
        out["sun_name"] = elem.attrib["name"].strip()
        if "meaning" in elem.attrib:
            out["sun_mean"] = elem.attrib["meaning"].strip()
        out["sun_ord"] = int(elem.attrib["ord"])
        out["sun_text"] = parse_body(elem)
    elif elem.attrib["type"] == "week":
        out["week_title"] = elem.attrib["name"].strip()
    else:
        raise ValueError("Unknown DAY type = %s", elem.attrib["type"])


def parse_file(filename):
    tree = et.parse(filename).getroot()
    article_dict = {}
    env = jinja2.Environment(loader=jinja2.FileSystemLoader("templates"))
    template = env.get_template("czech.html")

    for los in tree.iter("LOSUNG"):
        key, text = parse_losung(los)
        article_dict[key] = text

    for los in tree.iter("DAY"):
        parse_day(los, article_dict)

    article_list = []
    for key in sorted(article_dict.keys()):
        article_list.append(article_dict[key])
    return template.render(articles=article_list)


if __name__ == "__main__":
    print(parse_file(sys.argv[1]))