You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

310 lines
12 KiB

  1. #!/usr/bin/env python3
  2. # Kosmorro - Compute The Next Ephemerides
  3. # Copyright (C) 2019 Jérôme Deuchnord <jerome@deuchnord.fr>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. from abc import ABC, abstractmethod
  18. import datetime
  19. import json
  20. import os
  21. from tabulate import tabulate
  22. from skyfield.timelib import Time
  23. from numpy import int64
  24. from termcolor import colored
  25. from .data import Object, AsterEphemerides, MoonPhase, Event
  26. from .i18n import _
  27. from .version import VERSION
  28. from .exceptions import UnavailableFeatureError
  29. try:
  30. from latex import build_pdf
  31. except ImportError:
  32. build_pdf = None
  33. FULL_DATE_FORMAT = _('{day_of_week} {month} {day_number}, {year}').format(day_of_week='%A', month='%B',
  34. day_number='%d', year='%Y')
  35. TIME_FORMAT = _('{hours}:{minutes}').format(hours='%H', minutes='%M')
  36. class Dumper(ABC):
  37. def __init__(self, ephemeris: dict, events: [Event], date: datetime.date = datetime.date.today(),
  38. with_colors: bool = True):
  39. self.ephemeris = ephemeris
  40. self.events = events
  41. self.date = date
  42. self.with_colors = with_colors
  43. def get_date_as_string(self, capitalized: bool = False) -> str:
  44. date = self.date.strftime(FULL_DATE_FORMAT)
  45. if capitalized:
  46. return ''.join([date[0].upper(), date[1:]])
  47. return date
  48. @abstractmethod
  49. def to_string(self):
  50. pass
  51. @staticmethod
  52. def is_file_output_needed() -> bool:
  53. return False
  54. class JsonDumper(Dumper):
  55. def to_string(self):
  56. self.ephemeris['events'] = self.events
  57. self.ephemeris['ephemerides'] = self.ephemeris.pop('details')
  58. return json.dumps(self.ephemeris,
  59. default=self._json_default,
  60. indent=4)
  61. @staticmethod
  62. def _json_default(obj):
  63. # Fixes the "TypeError: Object of type int64 is not JSON serializable"
  64. # See https://stackoverflow.com/a/50577730
  65. if isinstance(obj, int64):
  66. return int(obj)
  67. if isinstance(obj, Time):
  68. return obj.utc_iso()
  69. if isinstance(obj, Object):
  70. obj = obj.__dict__
  71. obj.pop('skyfield_name')
  72. obj['object'] = obj.pop('name')
  73. obj['details'] = obj.pop('ephemerides')
  74. return obj
  75. if isinstance(obj, AsterEphemerides):
  76. return obj.__dict__
  77. if isinstance(obj, MoonPhase):
  78. moon_phase = obj.__dict__
  79. moon_phase['phase'] = moon_phase.pop('identifier')
  80. moon_phase['date'] = moon_phase.pop('time')
  81. return moon_phase
  82. if isinstance(obj, Event):
  83. event = obj.__dict__
  84. event['objects'] = [object.name for object in event['objects']]
  85. return event
  86. raise TypeError('Object of type "%s" could not be integrated in the JSON' % str(type(obj)))
  87. class TextDumper(Dumper):
  88. def to_string(self):
  89. text = [self.style(self.get_date_as_string(capitalized=True), 'h1')]
  90. if len(self.ephemeris['details']) > 0:
  91. text.append(self.get_asters(self.ephemeris['details']))
  92. text.append(self.get_moon(self.ephemeris['moon_phase']))
  93. if len(self.events) > 0:
  94. text.append('\n'.join([self.style(_('Expected events:'), 'h2'),
  95. self.get_events(self.events)]))
  96. text.append(self.style(_('Note: All the hours are given in UTC.'), 'em'))
  97. return '\n\n'.join(text)
  98. def style(self, text: str, tag: str) -> str:
  99. if not self.with_colors:
  100. return text
  101. styles = {
  102. 'h1': lambda t: colored(t, 'yellow', attrs=['bold']),
  103. 'h2': lambda t: colored(t, 'magenta', attrs=['bold']),
  104. 'th': lambda t: colored(t, 'white', attrs=['bold']),
  105. 'strong': lambda t: colored(t, attrs=['bold']),
  106. 'em': lambda t: colored(t, attrs=['dark'])
  107. }
  108. return styles[tag](text)
  109. def get_asters(self, asters: [Object]) -> str:
  110. data = []
  111. for aster in asters:
  112. name = self.style(aster.name, 'th')
  113. if aster.ephemerides.rise_time is not None:
  114. planet_rise = aster.ephemerides.rise_time.utc_strftime(TIME_FORMAT)
  115. else:
  116. planet_rise = '-'
  117. if aster.ephemerides.culmination_time is not None:
  118. planet_culmination = aster.ephemerides.culmination_time.utc_strftime(TIME_FORMAT)
  119. else:
  120. planet_culmination = '-'
  121. if aster.ephemerides.set_time is not None:
  122. planet_set = aster.ephemerides.set_time.utc_strftime(TIME_FORMAT)
  123. else:
  124. planet_set = '-'
  125. data.append([name, planet_rise, planet_culmination, planet_set])
  126. return tabulate(data, headers=[self.style(_('Object'), 'th'),
  127. self.style(_('Rise time'), 'th'),
  128. self.style(_('Culmination time'), 'th'),
  129. self.style(_('Set time'), 'th')],
  130. tablefmt='simple', stralign='center', colalign=('left',))
  131. def get_events(self, events: [Event]) -> str:
  132. data = []
  133. for event in events:
  134. data.append([self.style(event.start_time.utc_strftime(TIME_FORMAT), 'th'),
  135. event.get_description()])
  136. return tabulate(data, tablefmt='plain', stralign='left')
  137. def get_moon(self, moon_phase: MoonPhase) -> str:
  138. current_moon_phase = ' '.join([self.style(_('Moon phase:'), 'strong'), moon_phase.get_phase()])
  139. new_moon_phase = _('{next_moon_phase} on {next_moon_phase_date} at {next_moon_phase_time}').format(
  140. next_moon_phase=moon_phase.get_next_phase(),
  141. next_moon_phase_date=moon_phase.next_phase_date.utc_strftime(FULL_DATE_FORMAT),
  142. next_moon_phase_time=moon_phase.next_phase_date.utc_strftime(TIME_FORMAT)
  143. )
  144. return '\n'.join([current_moon_phase, new_moon_phase])
  145. class _LatexDumper(Dumper):
  146. def to_string(self):
  147. template_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  148. 'assets', 'pdf', 'template.tex')
  149. with open(template_path, mode='r') as file:
  150. template = file.read()
  151. return self._make_document(template)
  152. def _make_document(self, template: str) -> str:
  153. kosmorro_logo_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  154. 'assets', 'png', 'kosmorro-logo.png')
  155. moon_phase_graphics = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  156. 'assets', 'moonphases', 'png',
  157. '.'.join([self.ephemeris['moon_phase'].identifier.lower().replace('_', '-'),
  158. 'png']))
  159. document = template
  160. if len(self.ephemeris['details']) == 0:
  161. document = self._remove_section(document, 'ephemerides')
  162. if len(self.events) == 0:
  163. document = self._remove_section(document, 'events')
  164. document = document \
  165. .replace('+++KOSMORRO-VERSION+++', VERSION) \
  166. .replace('+++KOSMORRO-LOGO+++', kosmorro_logo_path) \
  167. .replace('+++DOCUMENT-TITLE+++', _('A Summary of your Sky')) \
  168. .replace('+++DOCUMENT-DATE+++', self.get_date_as_string(capitalized=True)) \
  169. .replace('+++INTRODUCTION+++',
  170. '\n\n'.join([
  171. _("This document summarizes the ephemerides and the events of {date}. "
  172. "It aims to help you to prepare your observation session.").format(
  173. date=self.get_date_as_string()),
  174. _("Don't forget to check the weather forecast before you go out with your material.")
  175. ])) \
  176. .replace('+++SECTION-EPHEMERIDES+++', _('Ephemerides of the day')) \
  177. .replace('+++EPHEMERIDES-OBJECT+++', _('Object')) \
  178. .replace('+++EPHEMERIDES-RISE-TIME+++', _('Rise time')) \
  179. .replace('+++EPHEMERIDES-CULMINATION-TIME+++', _('Culmination time')) \
  180. .replace('+++EPHEMERIDES-SET-TIME+++', _('Set time')) \
  181. .replace('+++EPHEMERIDES+++', self._make_ephemerides()) \
  182. .replace('+++MOON-PHASE-GRAPHICS+++', moon_phase_graphics) \
  183. .replace('+++CURRENT-MOON-PHASE-TITLE+++', _('Moon phase:')) \
  184. .replace('+++CURRENT-MOON-PHASE+++', self.ephemeris['moon_phase'].get_phase()) \
  185. .replace('+++SECTION-EVENTS+++', _('Expected events')) \
  186. .replace('+++EVENTS+++', self._make_events())
  187. return document
  188. def _make_ephemerides(self) -> str:
  189. latex = []
  190. for aster in self.ephemeris['details']:
  191. if aster.ephemerides.rise_time is not None:
  192. aster_rise = aster.ephemerides.rise_time.utc_strftime(TIME_FORMAT)
  193. else:
  194. aster_rise = '-'
  195. if aster.ephemerides.culmination_time is not None:
  196. aster_culmination = aster.ephemerides.culmination_time.utc_strftime(TIME_FORMAT)
  197. else:
  198. aster_culmination = '-'
  199. if aster.ephemerides.set_time is not None:
  200. aster_set = aster.ephemerides.set_time.utc_strftime(TIME_FORMAT)
  201. else:
  202. aster_set = '-'
  203. latex.append(r'\object{%s}{%s}{%s}{%s}' % (aster.name,
  204. aster_rise,
  205. aster_culmination,
  206. aster_set))
  207. return ''.join(latex)
  208. def _make_events(self) -> str:
  209. latex = []
  210. for event in self.events:
  211. latex.append(r'\event{%s}{%s}' % (event.start_time.utc_strftime(TIME_FORMAT),
  212. event.get_description()))
  213. return ''.join(latex)
  214. @staticmethod
  215. def _remove_section(document: str, section: str):
  216. begin_section_tag = '%%%%%% BEGIN-%s-SECTION' % section.upper()
  217. end_section_tag = '%%%%%% END-%s-SECTION' % section.upper()
  218. document = document.split('\n')
  219. new_document = []
  220. ignore_line = False
  221. for line in document:
  222. if begin_section_tag in line or end_section_tag in line:
  223. ignore_line = not ignore_line
  224. continue
  225. if ignore_line:
  226. continue
  227. new_document.append(line)
  228. return '\n'.join(new_document)
  229. class PdfDumper(Dumper):
  230. def to_string(self):
  231. try:
  232. latex_dumper = _LatexDumper(self.ephemeris, self.events, self.date, self.with_colors)
  233. return self._compile(latex_dumper.to_string())
  234. except RuntimeError:
  235. raise UnavailableFeatureError(_("Building PDFs was not possible, because some dependencies are not"
  236. " installed.\nPlease look at the documentation at http://kosmorro.space "
  237. "for more information."))
  238. @staticmethod
  239. def is_file_output_needed() -> bool:
  240. return True
  241. @staticmethod
  242. def _compile(latex_input) -> bytes:
  243. if build_pdf is None:
  244. raise RuntimeError('Python latex module not found')
  245. return bytes(build_pdf(latex_input))