slidegen.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. try:
  29. import config.config as const # pyright: ignore [reportMissingImports]
  30. except ModuleNotFoundError:
  31. log("no costom config found, using defaults")
  32. import config.default_config as const
  33. class Slidegen:
  34. def __init__(
  35. self, song_template_form, start_slide_form, song_slide_form
  36. ) -> None:
  37. self.metadata: dict = {"": ""}
  38. self.songtext: dict = {"": ""}
  39. self.song_file_path: str = ""
  40. self.song_file_content: list = []
  41. self.output_dir: str = ""
  42. self.chosen_structure: list | str = ""
  43. self.generated_slides: list = []
  44. self.song_template_form = song_template_form
  45. self.start_slide_form = start_slide_form
  46. self.song_slide_form = song_slide_form
  47. self.parse_argv()
  48. def execute(self) -> None:
  49. self.parse_file()
  50. self.calculate_desired_structures()
  51. self.generate_slides()
  52. def generate_slides(self) -> None:
  53. song_template = self.song_template_form()
  54. log("generating template...")
  55. template_img = song_template.get_template(self.metadata["title"])
  56. first_slide = self.start_slide_form()
  57. log("generating start slide...")
  58. start_slide_img = first_slide.get_slide(
  59. template_img,
  60. self.metadata["book"],
  61. self.metadata["text"],
  62. self.metadata["melody"],
  63. )
  64. start_slide_img.format = const.IMAGE_FORMAT
  65. try:
  66. start_slide_img.save(
  67. filename=path.join(
  68. self.output_dir,
  69. const.FILE_NAMEING + "1." + const.FILE_EXTENSION,
  70. )
  71. )
  72. except BlobError:
  73. error_msg("could not write start slide to target directory")
  74. log("generating song slides...")
  75. # unique_structures: list = list(set(self.chosen_structure))
  76. # count number of slides to be generated
  77. slide_count: int = 0
  78. for structure in self.chosen_structure:
  79. line_count: int = len(self.songtext[structure].splitlines())
  80. if line_count > const.STRUCTURE_ELEMENT_MAX_LINES:
  81. slide_count += (
  82. line_count // const.STRUCTURE_ELEMENT_MAX_LINES + 1
  83. )
  84. else:
  85. slide_count += 1
  86. current_slide_index: int = 0
  87. for index, structure in enumerate(self.chosen_structure):
  88. structure_element_splitted: list = self.songtext[
  89. structure
  90. ].splitlines()
  91. line_count = len(structure_element_splitted)
  92. use_line_ranges_per_index = []
  93. use_lines_per_index = []
  94. if line_count <= const.STRUCTURE_ELEMENT_MAX_LINES:
  95. inner_slide_count = 1
  96. else:
  97. inner_slide_count: int = (
  98. line_count // const.STRUCTURE_ELEMENT_MAX_LINES + 1
  99. )
  100. use_lines_per_index = [
  101. line_count // inner_slide_count
  102. ] * inner_slide_count
  103. for inner_slide in range(inner_slide_count):
  104. if sum(use_lines_per_index) == line_count:
  105. break
  106. use_lines_per_index[inner_slide] = (
  107. use_lines_per_index[inner_slide] + 1
  108. )
  109. for inner_slide in range(inner_slide_count):
  110. use_line_ranges_per_index.append(
  111. sum(use_lines_per_index[:inner_slide])
  112. )
  113. for inner_slide in range(inner_slide_count):
  114. current_slide_index += 1
  115. log(
  116. "generating song slide [{} / {}]...".format(
  117. current_slide_index, slide_count
  118. )
  119. )
  120. if inner_slide_count == 1:
  121. structure_element_value: str = self.songtext[structure]
  122. else:
  123. splitted_wanted_range: list = structure_element_splitted[
  124. use_line_ranges_per_index[
  125. inner_slide
  126. ] : use_line_ranges_per_index[inner_slide]
  127. + use_lines_per_index[inner_slide]
  128. ]
  129. structure_element_value: str = ""
  130. for element in splitted_wanted_range:
  131. structure_element_value += element + "\n"
  132. structure_element_value = structure_element_value[:-1]
  133. song_slide = self.song_slide_form()
  134. song_slide_img = song_slide.get_slide(
  135. template_img,
  136. structure_element_value,
  137. self.chosen_structure,
  138. index,
  139. bool(
  140. inner_slide_count != 1
  141. and inner_slide != inner_slide_count - 1
  142. ),
  143. )
  144. song_slide_img.format = const.IMAGE_FORMAT
  145. try:
  146. song_slide_img.save(
  147. filename=path.join(
  148. self.output_dir,
  149. const.FILE_NAMEING
  150. + str(current_slide_index + 1)
  151. + "."
  152. + const.FILE_EXTENSION,
  153. )
  154. )
  155. except BlobError:
  156. error_msg("could not write slide to target directory")
  157. def parse_file(self) -> None:
  158. self.parse_metadata()
  159. self.parse_songtext()
  160. def parse_metadata(self) -> None:
  161. metadata_dict = dict.fromkeys(const.METADATA_STRINGS)
  162. try:
  163. with open(self.song_file_path, mode="r", encoding="utf8") as opener:
  164. content = opener.readlines()
  165. except IOError:
  166. error_msg(
  167. "could not read the the song input file: '{}'".format(
  168. self.song_file_path
  169. )
  170. )
  171. valid_metadata_strings = list(const.METADATA_STRINGS)
  172. for line_nr, line in enumerate(content):
  173. if len(valid_metadata_strings) == 0:
  174. content = content[line_nr:]
  175. break
  176. if not re.match(
  177. r"^(?!structure)\S+: .+|^structure: ([0-9]+|R)(,([0-9]+|R))+$",
  178. line,
  179. ):
  180. if line[-1] == "\n":
  181. line = line[:-1]
  182. missing_metadata_strs = ""
  183. for metadata_str in valid_metadata_strings:
  184. missing_metadata_strs += ", " + metadata_str
  185. missing_metadata_strs = missing_metadata_strs[2:]
  186. error_msg(
  187. "invalid metadata syntax on line {}:\n{}\nThe ".format(
  188. line_nr + 1, line
  189. )
  190. + "following metadata strings are still missing: {}".format(
  191. missing_metadata_strs
  192. )
  193. )
  194. metadata_str = line[: line.index(":")]
  195. if metadata_str in valid_metadata_strings:
  196. metadata_dict[metadata_str] = line[line.index(": ") + 2 : -1]
  197. valid_metadata_strings.remove(metadata_str)
  198. continue
  199. error_msg("invalid metadata string '{}'".format(metadata_str))
  200. self.metadata = metadata_dict
  201. self.song_file_content = content
  202. def parse_songtext(self) -> None:
  203. unique_structures = get_unique_structure_elements(
  204. structure_as_list(self.metadata["structure"])
  205. )
  206. output_dict = dict.fromkeys(unique_structures)
  207. for structure in unique_structures:
  208. output_dict[structure] = get_songtext_by_structure(
  209. self.song_file_content, structure
  210. )
  211. self.songtext = output_dict
  212. def calculate_desired_structures(self) -> None:
  213. full_structure_str = str(self.metadata["structure"])
  214. full_structure_list = structure_as_list(full_structure_str)
  215. if len(self.chosen_structure) == 0:
  216. self.chosen_structure = structure_as_list(full_structure_str)
  217. log("chosen structure: {}".format(str(self.chosen_structure)))
  218. return
  219. if not "-" in self.chosen_structure:
  220. self.chosen_structure = structure_as_list(
  221. str(self.chosen_structure)
  222. )
  223. log("chosen structure: {}".format(str(self.chosen_structure)))
  224. return
  225. dash_index = str(self.chosen_structure).find("-")
  226. start_verse = str(self.chosen_structure[:dash_index]).strip()
  227. end_verse = str(self.chosen_structure[dash_index + 1 :]).strip()
  228. try:
  229. if int(start_verse) >= int(end_verse):
  230. error_msg("{} < {} must be true".format(start_verse, end_verse))
  231. if start_verse not in full_structure_str:
  232. error_msg("structure {} unknown".format(start_verse))
  233. if end_verse not in full_structure_str:
  234. error_msg("structure {} unknown".format(end_verse))
  235. except (ValueError, IndexError):
  236. error_msg("please choose a valid integer for the song structure")
  237. start_index = full_structure_list.index(start_verse)
  238. if start_index != 0:
  239. if (
  240. full_structure_list[0] == "R"
  241. and full_structure_list[start_index - 1] == "R"
  242. ):
  243. start_index -= 1
  244. end_index = full_structure_list.index(end_verse)
  245. if end_index != len(full_structure_list) - 1:
  246. if (
  247. full_structure_list[-1] == "R"
  248. and full_structure_list[end_index + 1] == "R"
  249. ):
  250. end_index += 1
  251. self.chosen_structure = full_structure_list[start_index : end_index + 1]
  252. log("chosen structure: {}".format(str(self.chosen_structure)))
  253. def parse_argv(self) -> None:
  254. try:
  255. self.song_file_path = sys.argv[1]
  256. self.output_dir = sys.argv[2]
  257. except IndexError:
  258. error_msg("incorrect amount of arguments provided, exiting...")
  259. try:
  260. self.chosen_structure = sys.argv[3]
  261. if self.chosen_structure.strip() == "":
  262. self.chosen_structure = ""
  263. except IndexError:
  264. self.chosen_structure = ""
  265. log("parsing {}...".format(self.song_file_path))
  266. def main() -> None:
  267. colorama.init()
  268. slidegen: Slidegen = Slidegen(
  269. ClassicSongTemplate, ClassicStartSlide, ClassicSongSlide
  270. )
  271. slidegen.execute()
  272. if __name__ == "__main__":
  273. main()