您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

431 行
18 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 pathlib import Path
  22. from tabulate import tabulate
  23. from numpy import int64
  24. from termcolor import colored
  25. from .data import ASTERS, 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. SHORT_DATETIME_FORMAT = _('{month} {day_number}, {hours}:{minutes}').format(month='%b', day_number='%d',
  36. hours='%H', minutes='%M')
  37. TIME_FORMAT = _('{hours}:{minutes}').format(hours='%H', minutes='%M')
  38. class Dumper(ABC):
  39. def __init__(self, ephemerides: [AsterEphemerides] = None, moon_phase: MoonPhase = None, events: [Event] = None,
  40. date: datetime.date = datetime.date.today(), timezone: int = 0, with_colors: bool = True,
  41. show_graph: bool = False):
  42. self.ephemerides = ephemerides
  43. self.moon_phase = moon_phase
  44. self.events = events
  45. self.date = date
  46. self.timezone = timezone
  47. self.with_colors = with_colors
  48. self.show_graph = show_graph
  49. if self.timezone != 0:
  50. self._convert_dates_to_timezones()
  51. def _convert_dates_to_timezones(self):
  52. if self.moon_phase.time is not None:
  53. self.moon_phase.time = self._datetime_to_timezone(self.moon_phase.time)
  54. if self.moon_phase.next_phase_date is not None:
  55. self.moon_phase.next_phase_date = self._datetime_to_timezone(
  56. self.moon_phase.next_phase_date)
  57. if self.ephemerides is not None:
  58. for ephemeris in self.ephemerides:
  59. if ephemeris.rise_time is not None:
  60. ephemeris.rise_time = self._datetime_to_timezone(ephemeris.rise_time)
  61. if ephemeris.culmination_time is not None:
  62. ephemeris.culmination_time = self._datetime_to_timezone(ephemeris.culmination_time)
  63. if ephemeris.set_time is not None:
  64. ephemeris.set_time = self._datetime_to_timezone(ephemeris.set_time)
  65. for event in self.events:
  66. event.start_time = self._datetime_to_timezone(event.start_time)
  67. if event.end_time is not None:
  68. event.end_time = self._datetime_to_timezone(event.end_time)
  69. def _datetime_to_timezone(self, time: datetime.datetime):
  70. return time.replace(tzinfo=datetime.timezone.utc).astimezone(
  71. tz=datetime.timezone(
  72. datetime.timedelta(
  73. hours=self.timezone
  74. )
  75. )
  76. )
  77. def get_date_as_string(self, capitalized: bool = False) -> str:
  78. date = self.date.strftime(FULL_DATE_FORMAT)
  79. if capitalized:
  80. return ''.join([date[0].upper(), date[1:]])
  81. return date
  82. @abstractmethod
  83. def to_string(self):
  84. pass
  85. @staticmethod
  86. def is_file_output_needed() -> bool:
  87. return False
  88. class JsonDumper(Dumper):
  89. def to_string(self):
  90. return json.dumps({
  91. 'ephemerides': [ephemeris.serialize() for ephemeris in self.ephemerides],
  92. 'moon_phase': self.moon_phase.serialize(),
  93. 'events': [event.serialize() for event in self.events]
  94. }, indent=4)
  95. @staticmethod
  96. def _json_default(obj):
  97. # Fixes the "TypeError: Object of type int64 is not JSON serializable"
  98. # See https://stackoverflow.com/a/50577730
  99. if isinstance(obj, int64):
  100. return int(obj)
  101. if isinstance(obj, datetime.datetime):
  102. return obj.isoformat()
  103. if isinstance(obj, Object):
  104. obj = obj.__dict__
  105. obj.pop('skyfield_name')
  106. obj.pop('radius')
  107. obj['object'] = obj.pop('name')
  108. obj['details'] = obj.pop('ephemerides')
  109. return obj
  110. if isinstance(obj, AsterEphemerides):
  111. return obj.__dict__
  112. if isinstance(obj, MoonPhase):
  113. moon_phase = obj.__dict__
  114. moon_phase['phase'] = moon_phase.pop('identifier')
  115. moon_phase['date'] = moon_phase.pop('time')
  116. return moon_phase
  117. if isinstance(obj, Event):
  118. event = obj.__dict__
  119. event['objects'] = [object.name for object in event['objects']]
  120. return event
  121. raise TypeError('Object of type "%s" could not be integrated in the JSON' % str(type(obj)))
  122. class TextDumper(Dumper):
  123. def to_string(self):
  124. text = [self.style(self.get_date_as_string(capitalized=True), 'h1')]
  125. if self.ephemerides is not None:
  126. text.append(self.stringify_ephemerides())
  127. text.append(self.get_moon(self.moon_phase))
  128. if len(self.events) > 0:
  129. text.append('\n'.join([self.style(_('Expected events:'), 'h2'),
  130. self.get_events(self.events)]))
  131. if self.timezone == 0:
  132. text.append(self.style(_('Note: All the hours are given in UTC.'), 'em'))
  133. else:
  134. tz_offset = str(self.timezone)
  135. if self.timezone > 0:
  136. tz_offset = ''.join(['+', tz_offset])
  137. text.append(self.style(_('Note: All the hours are given in the UTC{offset} timezone.').format(
  138. offset=tz_offset), 'em'))
  139. return '\n\n'.join(text)
  140. def style(self, text: str, tag: str) -> str:
  141. if not self.with_colors:
  142. return text
  143. styles = {
  144. 'h1': lambda t: colored(t, 'yellow', attrs=['bold']),
  145. 'h2': lambda t: colored(t, 'magenta', attrs=['bold']),
  146. 'th': lambda t: colored(t, 'white', attrs=['bold']),
  147. 'strong': lambda t: colored(t, attrs=['bold']),
  148. 'em': lambda t: colored(t, attrs=['dark'])
  149. }
  150. return styles[tag](text)
  151. def stringify_ephemerides(self) -> str:
  152. data = []
  153. for ephemeris in self.ephemerides:
  154. name = self.style(ephemeris.object.name, 'th')
  155. if ephemeris.rise_time is not None:
  156. time_fmt = TIME_FORMAT if ephemeris.rise_time.day == self.date.day else SHORT_DATETIME_FORMAT
  157. planet_rise = ephemeris.rise_time.strftime(time_fmt)
  158. else:
  159. planet_rise = '-'
  160. if ephemeris.culmination_time is not None:
  161. time_fmt = TIME_FORMAT if ephemeris.culmination_time.day == self.date.day \
  162. else SHORT_DATETIME_FORMAT
  163. planet_culmination = ephemeris.culmination_time.strftime(time_fmt)
  164. else:
  165. planet_culmination = '-'
  166. if ephemeris.set_time is not None:
  167. time_fmt = TIME_FORMAT if ephemeris.set_time.day == self.date.day else SHORT_DATETIME_FORMAT
  168. planet_set = ephemeris.set_time.strftime(time_fmt)
  169. else:
  170. planet_set = '-'
  171. data.append([name, planet_rise, planet_culmination, planet_set])
  172. return tabulate(data, headers=[self.style(_('Object'), 'th'),
  173. self.style(_('Rise time'), 'th'),
  174. self.style(_('Culmination time'), 'th'),
  175. self.style(_('Set time'), 'th')],
  176. tablefmt='simple', stralign='center', colalign=('left',))
  177. def get_events(self, events: [Event]) -> str:
  178. data = []
  179. for event in events:
  180. time_fmt = TIME_FORMAT if event.start_time.day == self.date.day else SHORT_DATETIME_FORMAT
  181. data.append([self.style(event.start_time.strftime(time_fmt), 'th'),
  182. event.get_description()])
  183. return tabulate(data, tablefmt='plain', stralign='left')
  184. def get_moon(self, moon_phase: MoonPhase) -> str:
  185. current_moon_phase = ' '.join([self.style(_('Moon phase:'), 'strong'), moon_phase.get_phase()])
  186. new_moon_phase = _('{next_moon_phase} on {next_moon_phase_date} at {next_moon_phase_time}').format(
  187. next_moon_phase=moon_phase.get_next_phase_name(),
  188. next_moon_phase_date=moon_phase.next_phase_date.strftime(FULL_DATE_FORMAT),
  189. next_moon_phase_time=moon_phase.next_phase_date.strftime(TIME_FORMAT)
  190. )
  191. return '\n'.join([current_moon_phase, new_moon_phase])
  192. class _LatexDumper(Dumper):
  193. def to_string(self):
  194. template_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  195. 'assets', 'pdf', 'template.tex')
  196. with open(template_path, mode='r') as file:
  197. template = file.read()
  198. return self._make_document(template)
  199. def _make_document(self, template: str) -> str:
  200. kosmorro_logo_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  201. 'assets', 'png', 'kosmorro-logo.png')
  202. moon_phase_graphics = os.path.join(os.path.abspath(os.path.dirname(__file__)),
  203. 'assets', 'moonphases', 'png',
  204. '.'.join([self.moon_phase.identifier.lower().replace('_', '-'),
  205. 'png']))
  206. document = template
  207. if self.ephemerides is None:
  208. document = self._remove_section(document, 'ephemerides')
  209. if len(self.events) == 0:
  210. document = self._remove_section(document, 'events')
  211. document = self.add_strings(document, kosmorro_logo_path, moon_phase_graphics)
  212. if self.show_graph:
  213. # The graphephemerides environment beginning tag must end with a percent symbol to ensure
  214. # that no extra space will interfere with the graph.
  215. document = document.replace(r'\begin{ephemerides}', r'\begin{graphephemerides}%')\
  216. .replace(r'\end{ephemerides}', r'\end{graphephemerides}')
  217. return document
  218. def add_strings(self, document, kosmorro_logo_path, moon_phase_graphics) -> str:
  219. document = document \
  220. .replace('+++KOSMORRO-VERSION+++', VERSION) \
  221. .replace('+++KOSMORRO-LOGO+++', kosmorro_logo_path) \
  222. .replace('+++DOCUMENT-TITLE+++', _('A Summary of your Sky')) \
  223. .replace('+++DOCUMENT-DATE+++', self.get_date_as_string(capitalized=True)) \
  224. .replace('+++INTRODUCTION+++',
  225. '\n\n'.join([
  226. _("This document summarizes the ephemerides and the events of {date}. "
  227. "It aims to help you to prepare your observation session. "
  228. "All the hours are given in {timezone}.").format(
  229. date=self.get_date_as_string(),
  230. timezone='UTC+%d' % self.timezone if self.timezone != 0 else 'UTC'
  231. ),
  232. _("Don't forget to check the weather forecast before you go out with your equipment.")
  233. ])) \
  234. .replace('+++SECTION-EPHEMERIDES+++', _('Ephemerides of the day')) \
  235. .replace('+++EPHEMERIDES-OBJECT+++', _('Object')) \
  236. .replace('+++EPHEMERIDES-RISE-TIME+++', _('Rise time')) \
  237. .replace('+++EPHEMERIDES-CULMINATION-TIME+++', _('Culmination time')) \
  238. .replace('+++EPHEMERIDES-SET-TIME+++', _('Set time')) \
  239. .replace('+++EPHEMERIDES+++', self._make_ephemerides()) \
  240. .replace('+++GRAPH_LABEL_HOURS+++', _('hours')) \
  241. .replace('+++MOON-PHASE-GRAPHICS+++', moon_phase_graphics) \
  242. .replace('+++CURRENT-MOON-PHASE-TITLE+++', _('Moon phase:')) \
  243. .replace('+++CURRENT-MOON-PHASE+++', self.moon_phase.get_phase()) \
  244. .replace('+++SECTION-EVENTS+++', _('Expected events')) \
  245. .replace('+++EVENTS+++', self._make_events())
  246. for aster in ASTERS:
  247. document = document.replace('+++ASTER_%s+++' % aster.skyfield_name.upper().split(' ')[0],
  248. aster.name)
  249. return document
  250. def _make_ephemerides(self) -> str:
  251. latex = []
  252. graph_y_component = 18
  253. if self.ephemerides is not None:
  254. for ephemeris in self.ephemerides:
  255. if ephemeris.rise_time is not None:
  256. time_fmt = TIME_FORMAT if ephemeris.rise_time.day == self.date.day else SHORT_DATETIME_FORMAT
  257. aster_rise = ephemeris.rise_time.strftime(time_fmt)
  258. else:
  259. aster_rise = '-'
  260. if ephemeris.culmination_time is not None:
  261. time_fmt = TIME_FORMAT if ephemeris.culmination_time.day == self.date.day\
  262. else SHORT_DATETIME_FORMAT
  263. aster_culmination = ephemeris.culmination_time.strftime(time_fmt)
  264. else:
  265. aster_culmination = '-'
  266. if ephemeris.set_time is not None:
  267. time_fmt = TIME_FORMAT if ephemeris.set_time.day == self.date.day else SHORT_DATETIME_FORMAT
  268. aster_set = ephemeris.set_time.strftime(time_fmt)
  269. else:
  270. aster_set = '-'
  271. if not self.show_graph:
  272. latex.append(r'\object{%s}{%s}{%s}{%s}' % (ephemeris.object.name,
  273. aster_rise,
  274. aster_culmination,
  275. aster_set))
  276. else:
  277. if ephemeris.rise_time is not None:
  278. raise_hour = ephemeris.rise_time.hour
  279. raise_minute = ephemeris.rise_time.minute
  280. else:
  281. raise_hour = raise_minute = 0
  282. aster_rise = ''
  283. if ephemeris.set_time is not None:
  284. set_hour = ephemeris.set_time.hour
  285. set_minute = ephemeris.set_time.minute
  286. else:
  287. set_hour = 24
  288. set_minute = 0
  289. aster_set = ''
  290. sets_after_end = set_hour > raise_hour
  291. if not sets_after_end:
  292. latex.append(r'\graphobject{%d}{gray}{0}{0}{%d}{%d}{}{%s}' % (graph_y_component,
  293. set_hour,
  294. set_minute,
  295. aster_set))
  296. set_hour = 24
  297. set_minute = 0
  298. latex.append(r'\graphobject{%d}{gray}{%d}{%d}{%d}{%d}{%s}{%s}' % (
  299. graph_y_component,
  300. raise_hour,
  301. raise_minute,
  302. set_hour,
  303. set_minute,
  304. aster_rise,
  305. aster_set if sets_after_end else ''
  306. ))
  307. graph_y_component -= 2
  308. return ''.join(latex)
  309. def _make_events(self) -> str:
  310. latex = []
  311. for event in self.events:
  312. latex.append(r'\event{%s}{%s}' % (event.start_time.strftime(TIME_FORMAT),
  313. event.get_description()))
  314. return ''.join(latex)
  315. @staticmethod
  316. def _remove_section(document: str, section: str):
  317. begin_section_tag = '%%%%%% BEGIN-%s-SECTION' % section.upper()
  318. end_section_tag = '%%%%%% END-%s-SECTION' % section.upper()
  319. document = document.split('\n')
  320. new_document = []
  321. ignore_line = False
  322. for line in document:
  323. if begin_section_tag in line or end_section_tag in line:
  324. ignore_line = not ignore_line
  325. continue
  326. if ignore_line:
  327. continue
  328. new_document.append(line)
  329. return '\n'.join(new_document)
  330. class PdfDumper(Dumper):
  331. def _convert_dates_to_timezones(self):
  332. """This method is disabled in this dumper, because the timezone is already converted
  333. in :class:`_LatexDumper`."""
  334. def to_string(self):
  335. try:
  336. latex_dumper = _LatexDumper(self.ephemerides, self.moon_phase, self.events,
  337. date=self.date, timezone=self.timezone, with_colors=self.with_colors,
  338. show_graph=self.show_graph)
  339. return self._compile(latex_dumper.to_string())
  340. except RuntimeError:
  341. raise UnavailableFeatureError(_("Building PDFs was not possible, because some dependencies are not"
  342. " installed.\nPlease look at the documentation at http://kosmorro.space "
  343. "for more information."))
  344. @staticmethod
  345. def is_file_output_needed() -> bool:
  346. return True
  347. @staticmethod
  348. def _compile(latex_input) -> bytes:
  349. if build_pdf is None:
  350. raise RuntimeError('Python latex module not found')
  351. package = str(Path(__file__).parent.absolute()) + '/assets/pdf/'
  352. return bytes(build_pdf(latex_input, [package]))