slidegen.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. #!/usr/bin/env python3
  2. """
  3. Copyright © 2022 Noah Vogt <noah@noahvogt.com>
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. """
  15. from os import path
  16. import re
  17. import sys
  18. import colorama
  19. from wand.exceptions import BlobError
  20. from utils import (
  21. log,
  22. error_msg,
  23. get_songtext_by_structure,
  24. structure_as_list,
  25. get_unique_structure_elements,
  26. )
  27. from slides import ClassicSongTemplate, ClassicStartSlide, ClassicSongSlide
  28. import config as const
  29. class Slidegen:
  30. def __init__(
  31. self, song_template_form, start_slide_form, song_slide_form
  32. ) -> None:
  33. self.metadata: dict = {"": ""}
  34. self.songtext: dict = {"": ""}
  35. self.song_file_path: str = ""
  36. self.song_file_content: list = []
  37. self.output_dir: str = ""
  38. self.chosen_structure: list | str = ""
  39. self.generated_slides: list = []
  40. self.song_template_form = song_template_form
  41. self.start_slide_form = start_slide_form
  42. self.song_slide_form = song_slide_form
  43. self.parse_argv()
  44. def execute(self) -> None:
  45. self.parse_file()
  46. self.calculate_desired_structures()
  47. self.generate_slides()
  48. def generate_slides(self) -> None:
  49. song_template = self.song_template_form()
  50. log("generating template...")
  51. template_img = song_template.get_template(self.metadata["title"])
  52. first_slide = self.start_slide_form()
  53. log("generating start slide...")
  54. start_slide_img = first_slide.get_slide(
  55. template_img,
  56. self.metadata["book"],
  57. self.metadata["text"],
  58. self.metadata["melody"],
  59. )
  60. start_slide_img.format = const.IMAGE_FORMAT
  61. try:
  62. start_slide_img.save(
  63. filename=path.join(
  64. self.output_dir,
  65. const.FILE_NAMEING + "1." + const.FILE_EXTENSION,
  66. )
  67. )
  68. except BlobError:
  69. error_msg("could not write start slide to target directory")
  70. log("generating song slides...")
  71. # unique_structures: list = list(set(self.chosen_structure))
  72. # count number of slides to be generated
  73. slide_count: int = 0
  74. for structure in self.chosen_structure:
  75. line_count: int = len(self.songtext[structure].splitlines())
  76. if line_count > const.STRUCTURE_ELEMENT_MAX_LINES:
  77. slide_count += (
  78. line_count // const.STRUCTURE_ELEMENT_MAX_LINES + 1
  79. )
  80. else:
  81. slide_count += 1
  82. current_slide_index: int = 0
  83. for index, structure in enumerate(self.chosen_structure):
  84. structure_element_splitted: list = self.songtext[
  85. structure
  86. ].splitlines()
  87. line_count = len(structure_element_splitted)
  88. use_line_ranges_per_index = []
  89. use_lines_per_index = []
  90. if line_count <= const.STRUCTURE_ELEMENT_MAX_LINES:
  91. inner_slide_count = 1
  92. else:
  93. inner_slide_count: int = (
  94. line_count // const.STRUCTURE_ELEMENT_MAX_LINES + 1
  95. )
  96. use_lines_per_index = [
  97. line_count // inner_slide_count
  98. ] * inner_slide_count
  99. for inner_slide in range(inner_slide_count):
  100. if sum(use_lines_per_index) == line_count:
  101. break
  102. use_lines_per_index[inner_slide] = (
  103. use_lines_per_index[inner_slide] + 1
  104. )
  105. for inner_slide in range(inner_slide_count):
  106. use_line_ranges_per_index.append(
  107. sum(use_lines_per_index[:inner_slide])
  108. )
  109. for inner_slide in range(inner_slide_count):
  110. current_slide_index += 1
  111. log(
  112. "generating song slide [{} / {}]...".format(
  113. current_slide_index, slide_count
  114. )
  115. )
  116. if inner_slide_count == 1:
  117. structure_element_value: str = self.songtext[structure]
  118. else:
  119. splitted_wanted_range: list = structure_element_splitted[
  120. use_line_ranges_per_index[
  121. inner_slide
  122. ] : use_line_ranges_per_index[inner_slide]
  123. + use_lines_per_index[inner_slide]
  124. ]
  125. structure_element_value: str = ""
  126. for element in splitted_wanted_range:
  127. structure_element_value += element + "\n"
  128. structure_element_value = structure_element_value[:-1]
  129. song_slide = self.song_slide_form()
  130. song_slide_img = song_slide.get_slide(
  131. template_img,
  132. structure_element_value,
  133. self.chosen_structure,
  134. index,
  135. bool(
  136. inner_slide_count != 1
  137. and inner_slide != inner_slide_count - 1
  138. ),
  139. )
  140. song_slide_img.format = const.IMAGE_FORMAT
  141. try:
  142. song_slide_img.save(
  143. filename=path.join(
  144. self.output_dir,
  145. const.FILE_NAMEING
  146. + str(current_slide_index + 1)
  147. + "."
  148. + const.FILE_EXTENSION,
  149. )
  150. )
  151. except BlobError:
  152. error_msg("could not write slide to target directory")
  153. def parse_file(self) -> None:
  154. self.parse_metadata()
  155. self.parse_songtext()
  156. def parse_metadata(self) -> None:
  157. metadata_dict = dict.fromkeys(const.METADATA_STRINGS)
  158. try:
  159. with open(self.song_file_path, mode="r", encoding="utf8") as opener:
  160. content = opener.readlines()
  161. except IOError:
  162. error_msg(
  163. "could not read the the song input file: '{}'".format(
  164. self.song_file_path
  165. )
  166. )
  167. valid_metadata_strings = list(const.METADATA_STRINGS)
  168. for line_nr, line in enumerate(content):
  169. if len(valid_metadata_strings) == 0:
  170. content = content[line_nr:]
  171. break
  172. if not re.match(
  173. r"^(?!structure)\S+: .+|^structure: ([0-9]+|R)(,([0-9]+|R))+$",
  174. line,
  175. ):
  176. if line[-1] == "\n":
  177. line = line[:-1]
  178. missing_metadata_strs = ""
  179. for metadata_str in valid_metadata_strings:
  180. missing_metadata_strs += ", " + metadata_str
  181. missing_metadata_strs = missing_metadata_strs[2:]
  182. error_msg(
  183. "invalid metadata syntax on line {}:\n{}\nThe ".format(
  184. line_nr + 1, line
  185. )
  186. + "following metadata strings are still missing: {}".format(
  187. missing_metadata_strs
  188. )
  189. )
  190. metadata_str = line[: line.index(":")]
  191. if metadata_str in valid_metadata_strings:
  192. metadata_dict[metadata_str] = line[line.index(": ") + 2 : -1]
  193. valid_metadata_strings.remove(metadata_str)
  194. continue
  195. error_msg("invalid metadata string '{}'".format(metadata_str))
  196. self.metadata = metadata_dict
  197. self.song_file_content = content
  198. def parse_songtext(self) -> None:
  199. unique_structures = get_unique_structure_elements(
  200. structure_as_list(self.metadata["structure"])
  201. )
  202. output_dict = dict.fromkeys(unique_structures)
  203. for structure in unique_structures:
  204. output_dict[structure] = get_songtext_by_structure(
  205. self.song_file_content, structure
  206. )
  207. self.songtext = output_dict
  208. def calculate_desired_structures(self) -> None:
  209. full_structure_str = str(self.metadata["structure"])
  210. full_structure_list = structure_as_list(full_structure_str)
  211. if len(self.chosen_structure) == 0:
  212. self.chosen_structure = structure_as_list(full_structure_str)
  213. log("chosen structure: {}".format(str(self.chosen_structure)))
  214. return
  215. if not "-" in self.chosen_structure:
  216. self.chosen_structure = structure_as_list(
  217. str(self.chosen_structure)
  218. )
  219. log("chosen structure: {}".format(str(self.chosen_structure)))
  220. return
  221. dash_index = str(self.chosen_structure).find("-")
  222. start_verse = str(self.chosen_structure[:dash_index]).strip()
  223. end_verse = str(self.chosen_structure[dash_index + 1 :]).strip()
  224. try:
  225. if int(start_verse) >= int(end_verse):
  226. error_msg("{} < {} must be true".format(start_verse, end_verse))
  227. if start_verse not in full_structure_str:
  228. error_msg("structure {} unknown".format(start_verse))
  229. if end_verse not in full_structure_str:
  230. error_msg("structure {} unknown".format(end_verse))
  231. except (ValueError, IndexError):
  232. error_msg("please choose a valid integer for the song structure")
  233. start_index = full_structure_list.index(start_verse)
  234. if start_index != 0:
  235. if (
  236. full_structure_list[0] == "R"
  237. and full_structure_list[start_index - 1] == "R"
  238. ):
  239. start_index -= 1
  240. end_index = full_structure_list.index(end_verse)
  241. if end_index != len(full_structure_list) - 1:
  242. if (
  243. full_structure_list[-1] == "R"
  244. and full_structure_list[end_index + 1] == "R"
  245. ):
  246. end_index += 1
  247. self.chosen_structure = full_structure_list[start_index : end_index + 1]
  248. log("chosen structure: {}".format(str(self.chosen_structure)))
  249. def parse_argv(self) -> None:
  250. try:
  251. self.song_file_path = sys.argv[1]
  252. self.output_dir = sys.argv[2]
  253. except IndexError:
  254. error_msg("incorrect amount of arguments provided, exiting...")
  255. try:
  256. self.chosen_structure = sys.argv[3]
  257. if self.chosen_structure.strip() == "":
  258. self.chosen_structure = ""
  259. except IndexError:
  260. self.chosen_structure = ""
  261. log("parsing {}...".format(self.song_file_path))
  262. def main() -> None:
  263. colorama.init()
  264. slidegen: Slidegen = Slidegen(
  265. ClassicSongTemplate, ClassicStartSlide, ClassicSongSlide
  266. )
  267. slidegen.execute()
  268. if __name__ == "__main__":
  269. main()