eskp.py
author Jens-Uwe Grooss <j.-u.grooss@fz-juelich.de>
Tue, 25 Jan 2022 09:49:34 +0100
changeset 1295 1650cb07309d
parent 1116 0559fcb555f1
child 1526 e90ee05eaf02
permissions -rwxr-xr-x
update script to year 2022 simulation
     1 # -*- coding: utf-8 -*-
     2 #!/usr/bin/env python
     3 import logging
     4 
     5 import os
     6 import codecs
     7 import vobject
     8 import StringIO
     9 
    10 import qrcode
    11 
    12 from docutils.core import publish_parts
    13 from flask import Flask
    14 from flask import render_template
    15 from flask import request
    16 from flask_babel import gettext as _
    17 from flask_babel import Babel
    18 from config import LANGUAGES
    19 
    20 import base64
    21 
    22 LANGUAGE_SELECTED = "de"
    23 # ToDo after engelish is implemented set LANGUAGE_SELECTED = None
    24 
    25 # We need the path of this file to find templates to translate
    26 ESKP_PATH = os.path.dirname(os.path.abspath(__file__))
    27 logging.basicConfig(filename=os.path.join(ESKP_PATH, 'eskp-app.log'), level=logging.DEBUG)
    28 FILES= os.listdir(os.path.join(ESKP_PATH, 'static/images/uvmap'))
    29 
    30 app = Flask(__name__)
    31 babel = Babel(app)
    32 
    33 app.config['BABEL_DEFAULT_LOCALE'] = 'de'
    34 
    35 
    36 def get_vcard(filename):
    37     filename = os.path.join(ESKP_PATH, filename)
    38     with codecs.open(filename, 'r', 'utf-8') as f:
    39         vcard = f.read()
    40     return vobject.readOne(vcard)
    41 
    42 
    43 def get_content(filename, overrides=None):
    44     content = u""
    45     filename = os.path.join(ESKP_PATH, filename)
    46     if os.path.isfile(filename):
    47         with codecs.open(filename, 'r', 'utf-8') as f:
    48             rst_data = f.read()
    49         content = publish_parts(rst_data, writer_name='html', settings_overrides=overrides)['html_body']
    50     return content
    51 
    52 def get_html_content(filename, overrides=None):
    53     html_content = u""
    54     filename = os.path.join(ESKP_PATH, filename)
    55     if os.path.isfile(filename):
    56         with codecs.open(filename, 'r', 'utf-8') as f:
    57             html_content = f.read()
    58 
    59     return html_content
    60 
    61 def get_newest_date():
    62     getdates = get_valid_dates(FILES)
    63     newest_date = getdates[-1]
    64 
    65     return newest_date
    66 
    67 
    68 def get_topmenue():
    69     newest_date = get_newest_date()
    70     menue = [
    71         ('/ozoneloss', _(u'Ozoneloss'),
    72          (('/ozoneloss', _(u'overview')),
    73           ('/ozoneloss/clams/2022', _(u'calculations')),
    74           ('/ozoneloss/vpsc/2022', _(u'estimations')),
    75           ('/ozoneloss/uvmap/' + newest_date, _(u'uv index map')),
    76           ('/ozoneloss/uvi', _(u'uv increase')),
    77           ('/ozoneloss/decadal', _(u'decadal')))),
    78         ('/eskp', _(u'ESKP'), (None, None)),
    79         ('/iek-7', _(u'IEK-7'), (None, None))
    80     ]
    81     return menue
    82 
    83 
    84 app.jinja_env.globals.update(get_topmenue=get_topmenue)
    85 
    86 
    87 def get_o3lossclams_dates():
    88     menue = [
    89         ('/ozoneloss/clams/2022', _(u'2022')),
    90         ('/ozoneloss/clams/2020', _(u'2020')),
    91         ('/ozoneloss/clams/2019', _(u'2019')),
    92         ('/ozoneloss/clams/2018', _(u'2018')),
    93         ('/ozoneloss/clams/2017', _(u'2017')),
    94         ('/ozoneloss/clams/2016', _(u'2016')),
    95         ('/ozoneloss/clams/2015', _(u'2015')),
    96         ('/ozoneloss/clams/2012', _(u'2012')),
    97         ('/ozoneloss/clams/2011', _(u'2011')),
    98         ('/ozoneloss/clams/2010', _(u'2010')),
    99     ]
   100     return menue
   101 
   102 
   103 def get_valid_dates(files):
   104     dates = []
   105 
   106     for file in files:
   107         if file.endswith('.png') and file.find('uvi') >= 0:
   108             date = file[-12:-6]
   109             dates.append(date)
   110     dates.sort()
   111     for date in dates:
   112         i = 0
   113         for param in ['uvi', 'o3col', 'do3col']:
   114             testfile = 'clams_' + param + '_' + date + '12.png'
   115             if files.count(testfile) > 0:
   116                 i = i + 1
   117         if i <> 3:
   118             dates.remove(date)
   119     return dates
   120 
   121 
   122 def get_o3lossuvmap_dates(date_show):
   123     dates = get_valid_dates(FILES)
   124     ndates = len(dates)
   125     ind = dates.index(date_show)
   126     navitexts = []
   127     if ind ==0 :
   128         chosendates = [dates[ind+1]]
   129         navitexts.append('next ->')
   130 
   131     elif ind >= ndates - 1:
   132         chosendates= [dates[ind-1]]
   133         navitexts.append('<- prev')
   134     else:
   135         chosendates = [dates[ind-1], dates[ind+1]]
   136         navitexts.append('<- prev')
   137         navitexts.append('next ->')
   138     menue = []
   139 
   140     for i in range(len(chosendates)):
   141         date = chosendates[i]
   142         navitext = navitexts[i]
   143         menue.append(('/ozoneloss/uvmap/' + date, _(navitext)))
   144     return menue
   145 
   146 
   147 def get_vpsc_dates():
   148     menue = [
   149         ('/ozoneloss/vpsc/2022', _(u'2022')),
   150         ('/ozoneloss/vpsc/2020', _(u'2020')),
   151         ('/ozoneloss/vpsc/2019', _(u'2019')),
   152         ('/ozoneloss/vpsc/2018', _(u'2018')),
   153         ('/ozoneloss/vpsc/2017', _(u'2017')),
   154         ('/ozoneloss/vpsc/2016', _(u'2016')),
   155         ('/ozoneloss/vpsc/2015', _(u'2015')),
   156         ('/ozoneloss/vpsc/2014', _(u'2014')),
   157         ('/ozoneloss/vpsc/2013', _(u'2013')),
   158         ('/ozoneloss/vpsc/2012', _(u'2012')),
   159         ('/ozoneloss/vpsc/2011', _(u'2011')),
   160         ('/ozoneloss/vpsc/2010', _(u'2010')),
   161     ]
   162     return menue
   163 
   164 
   165 app.jinja_env.globals.update(get_o3lossclams_dates=get_o3lossclams_dates)
   166 app.jinja_env.globals.update(get_vpsc_dates=get_vpsc_dates)
   167 app.jinja_env.globals.update(get_o3lossuvmap_dates=get_o3lossuvmap_dates)
   168 
   169 
   170 def modal_info(template, act, title, filename):
   171     content = get_content(filename)
   172     html = render_template(template, act=act, title=title, content=content, exit=_(u"Close"))
   173     return html
   174 
   175 
   176 @babel.localeselector
   177 def get_locale():
   178     requested_language = request.accept_languages.best_match(LANGUAGES.keys())
   179     if requested_language in ("de", "en"):
   180         return requested_language or "de"
   181 
   182 @app.route("/")
   183 @app.route("/index")
   184 def index():
   185     return render_template("/index.html",
   186                            eskp_info=_(u'About ESKP'),
   187                            )
   188 
   189 
   190 @app.route('/ozoneloss/clams/<year>')
   191 def ozoneloss_clams_year(year):
   192     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_clams.rst")
   193     content = get_content(filename)
   194     return render_template("/ozoneloss_clams.html", act="ozoneloss/clams/%s" % year, content=content, year=year)
   195 
   196 
   197 @app.route('/ozoneloss/uvmap/<date>')
   198 def ozoneloss_uvmap_date(date):
   199     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_uvmap.rst")
   200     content = get_content(filename)
   201     htmlfile = os.path.join("templates", get_locale(), "html", "uvi_table.html")
   202     html_table = get_html_content(htmlfile)
   203 
   204     return render_template("/ozoneloss_uvmap.html", act="ozoneloss/uvmap/%s" % date, content=content,
   205                            html_table=html_table, date=date)
   206 
   207 
   208 @app.route('/ozoneloss/vpsc/<year>')
   209 def ozoneloss_vpsc_year(year):
   210     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_vpsc.rst")
   211     content = get_content(filename)
   212     filename = os.path.join("templates", get_locale(), "rst", "explanation_vpsc.rst")
   213     explanation = get_content(filename)
   214 
   215     return render_template("/ozoneloss_vpsc.html", act="ozoneloss/vpsc/%s" % year, content=content,
   216                            content_explanation=explanation, year=year)
   217 
   218 
   219 @app.route('/de')
   220 def de():
   221     global LANGUAGE_SELECTED
   222     LANGUAGE_SELECTED = "de"
   223     return render_template("/index.html",
   224                            eskp_info=_(u'About ESKP'),
   225                            )
   226 
   227 
   228 @app.route('/en')
   229 def en():
   230     global LANGUAGE_SELECTED
   231     LANGUAGE_SELECTED = "en"
   232     return render_template("/index.html",
   233                            eskp_info=_(u'About ESKP'),
   234                            )
   235 
   236 
   237 @app.route("/eskp")
   238 def eskp():
   239     filename = os.path.join("templates", get_locale(), "rst", "eskp.rst")
   240     content = get_content(filename)
   241     filename = os.path.join("templates", get_locale(), "rst", "eskp_title.rst")
   242     headline = get_content(filename)
   243     return render_template("/eskp.html", act="eskp", content=content, headline=headline)
   244 
   245 
   246 def qr_image_data(card):
   247     buf = StringIO.StringIO()
   248     qr = qrcode.QRCode(
   249         version=1,
   250         error_correction=qrcode.constants.ERROR_CORRECT_L,
   251         box_size=2,
   252         border=2,
   253     )
   254     qr.add_data(card.serialize())
   255     qr.make(fit=True)
   256     img = qr.make_image()
   257     img.save(buf)
   258     image = buf.getvalue()
   259     return base64.b64encode(image)
   260 
   261 
   262 @app.route("/ozoneloss")
   263 def ozoneloss():
   264     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss.rst")
   265     content = get_content(filename)
   266     ref_date = "200119"
   267     newest_date = get_newest_date()
   268     content = content.replace(ref_date, newest_date, 1)
   269 
   270     vcard_file = os.path.join("vcards", "jug.vcf")
   271     author = u""
   272 
   273     try:
   274         card = get_vcard(vcard_file)
   275     except IOError:
   276         card = None
   277     if card is not None:
   278         qr_image = qr_image_data(card)
   279         author = render_template("/author_info.html", act="author", title=_(u"Ozoneloss"),
   280                                  card=card, image=qr_image, contact=_(u"Contact"), exit=_(u"Close"))
   281 
   282     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_publications.rst")
   283     publications = modal_info("/publications_info.html", "publications", _(u"Ozoneloss"), filename)
   284     return render_template("/ozoneloss.html", act="ozoneloss", content=content,
   285                            author=author, card=card, publications=publications)
   286 
   287 
   288 @app.route("/ozoneloss/clams")
   289 def ozoneloss_clams():
   290     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_clams.rst")
   291     content = get_content(filename)
   292     return render_template("/ozoneloss_clams.html", act="ozoneloss/clams", content=content)
   293 
   294 
   295 @app.route("/ozoneloss/uvmap")
   296 def ozoneloss_uvmap():
   297     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_uvmap.rst")
   298     content = get_content(filename)
   299 
   300     htmlfile = os.path.join("templates", get_locale(), "html", "uvi_table.html")
   301     html_content = get_html_content(htmlfile)
   302     return render_template("/ozoneloss_uvmap.html", act="ozoneloss/uvmap", content=content,
   303                            html_content=html_content)
   304 
   305 
   306 @app.route("/ozoneloss/vpsc")
   307 def ozoneloss_vpsc():
   308     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_vpsc.rst")
   309     content = get_content(filename)
   310     return render_template("/ozoneloss_vpsc.html", act="ozoneloss/vpsc", content=content)
   311 
   312 
   313 @app.route("/ozoneloss/uvi", methods=['GET'])
   314 def ozoneloss_uvi():
   315     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_uvi.rst")
   316     content = get_content(filename)
   317     htmlfile = os.path.join("templates", get_locale(), "html", "ozoneloss_uvi_form_start.html")
   318     html_content = get_html_content(htmlfile)
   319     htmlfile = os.path.join("templates", get_locale(), "html", "uvi_table.html")
   320     html_table = get_html_content(htmlfile)
   321 
   322     lat = 50.
   323     o3offset = 50.
   324     figname = "uvincr_lat%0.3i_do3%0.3i.svg" % (lat, o3offset)
   325 
   326     return render_template('ozoneloss_uvi.html', act="ozoneloss/uvi", content=content, figname=figname,
   327                            alt=_(u"UV increase at {{lat}} degrees N for {{o3offset}} DU ozone depletion"),
   328                                  html_content=html_content, html_table=html_table)
   329 
   330 
   331 @app.route("/ozoneloss/uvi_graph", methods=['POST'])
   332 def ozoneloss_uvi_graph():
   333     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_uvi.rst")
   334     content = get_content(filename)
   335     htmlfile = os.path.join("templates", get_locale(), "html", "ozoneloss_uvi_form.html")
   336     html_content = get_html_content(htmlfile)
   337     htmlfile = os.path.join("templates", get_locale(), "html", "uvi_table.html")
   338     html_table = get_html_content(htmlfile)
   339 
   340     latstr = request.form['Gradzahl']
   341     o3offsetstr = request.form['Dobson-Unit']
   342 
   343     latstr2 = latstr.replace(u'\xb0', '')
   344     if latstr2.endswith(u'N'):
   345         latstr2 = latstr2.replace(u'N', '')
   346         lat = float(latstr2)
   347     if latstr2.endswith(u'S'):
   348         latstr2 = latstr2.replace(u'S', '')
   349         lat = -float(latstr2)
   350         
   351     html_content = html_content.replace('{{latstr}}', latstr)
   352     html_content = html_content.replace('{{o3offsetstr}}', o3offsetstr)
   353     figname = "uvincr_lat%0.3i_do3%0.3i.svg" % (lat, float(o3offsetstr))
   354 
   355     return render_template('ozoneloss_uvi.html', act="ozoneloss_uvi_graph", content=content, figname=figname,
   356                            alt=_(u"UV increase at {{lat}} degrees N for {{o3offset}} DU ozone depletion"),
   357                            html_content=html_content, html_table=html_table)
   358 
   359 @app.route("/ozoneloss/decadal")
   360 def ozoneloss_decadal():
   361     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_decadal.rst")
   362     content = get_content(filename)
   363     filename = os.path.join("templates", get_locale(), "rst", "ozoneloss_decadal_bottom.rst")
   364     explanation = get_content(filename)
   365     
   366     return render_template("/ozoneloss_decadal.html", act="ozoneloss_decadal", content=content,
   367                            content_explanation=explanation)
   368 
   369 
   370 
   371 @app.route("/iek-7")
   372 def institute():
   373     filename = os.path.join("templates", get_locale(), "rst", "iek-7.rst")
   374     content = get_content(filename)
   375     vcard_file = os.path.join("vcards", "sas.vcf")
   376     author = u""
   377     try:
   378         card = get_vcard(vcard_file)
   379     except IOError:
   380         card = None
   381     if card is not None:
   382         qr_image = qr_image_data(card)
   383         author = render_template("/author_info.html", act="author", title=_(u"IEK-7"),
   384                                  card=card, image=qr_image, contact=_(u"Contact"), exit=_(u"Close"))
   385 
   386     return render_template("/iek-7.html", act="iek-7", content=content,
   387                            author=author, card=card, contact=u"IEK-7")
   388 
   389 
   390 @app.route("/imprint")
   391 def imprint():
   392     filename = os.path.join("templates", get_locale(), "rst", "imprint.rst")
   393     content = get_content(filename)
   394     return render_template("/content.html", act="imprint", content=content)
   395 
   396 
   397 @app.route("/dataprotection")
   398 def dataprotection():
   399     filename = os.path.join("templates", get_locale(), "rst", "datenschutz.rst")
   400     content = get_content(filename)
   401     return render_template("/content.html", act="datenschutz", content=content)
   402 
   403 
   404 @app.errorhandler(404)
   405 def page_not_found(e):
   406     msg = _(u"Url: %(url)s not found", url=request.url)
   407     info = _(u"This information is not available!")
   408     return render_template("404.html", msg=msg, info=info)
   409 
   410 
   411 if __name__ == "__main__":
   412     app.run(host='localhost', port=5014)
Impressum Datenschutzerklärung