示例#1
0
def get_ug_bl_dsos():
    global _ug_bl_dsos
    if not _ug_bl_dsos:
        ug_bl_dsos = {}

        for c in Constellation.get_all():
            ug_bl_dsos[c.id] = {}

        files = [f for f in sorted(glob.glob('app/static/webassets-external/users/glahn/img/dso/*.jpg'))] + \
            [f for f in sorted(glob.glob('app/static/webassets-external/users/laville/img/dso/*.jpg'))]

        for f in files:
            base_name = os.path.basename(f)
            if base_name.endswith('.jpg'):
                dso_name = base_name[:-len('.jpg')]
                normalized_name = normalize_dso_name(
                    denormalize_dso_name(dso_name))
                dso = DeepskyObject.query.filter_by(
                    name=normalized_name).first()
                if dso:
                    db.session.expunge(dso)
                    ug_bl_dsos[dso.constellation_id][dso.id] = dso

        _ug_bl_dsos = ug_bl_dsos
    return _ug_bl_dsos
示例#2
0
def _try_copy(f, appendix, img_dst_dir):
    if _has_known_prefix(f) and f.endswith(appendix):
        base_name = os.path.basename(f)[:-len(appendix)]
        idx = base_name.find('_')
        if idx >= 0:
            base_name = base_name[:idx]
        dso_file_name = normalize_dso_name(base_name)
        copyfile(f, os.path.join(img_dst_dir, dso_file_name + '.jpg'))
        return True
    return False
示例#3
0
def session_plan_import(session_plan_id):
    session_plan = SessionPlan.query.filter_by(id=session_plan_id).first()
    _check_session_plan(session_plan)

    if 'file' not in request.files:
        flash(gettext('No file part'), 'form-error')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash(gettext('No file selected'))
        return redirect(request.url)
    if file:
        is_oal = file.filename.lower().endswith('oal')
        filename = secure_filename(file.filename)
        path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        file.save(path)
        if is_oal:
            with open(path) as oalfile:
                log_warn, log_error = import_session_plan_items(
                    session_plan, oalfile)
            db.session.commit()
            flash(gettext('Session plan uploaded.'), 'form-success')
        else:
            with open(path) as csvfile:
                reader = csv.DictReader(csvfile,
                                        delimiter=';',
                                        fieldnames=['DSO_NAME'])
                existing_ids = set(item.dso_id
                                   for item in session_plan.session_plan_items)

                for row in reader:
                    dso_name = row['DSO_NAME']
                    if dso_name == 'none':
                        continue

                    dso_name = normalize_dso_name(dso_name)
                    dso = DeepskyObject.query.filter(
                        DeepskyObject.name == dso_name).first()

                    if dso and dso.id not in existing_ids:
                        if not session_plan.find_dso_by_id(dso.id):
                            user = get_anonymous_user(
                            ) if current_user.is_anonymous else current_user
                            new_item = session_plan.create_new_session_plan_item(
                                dso.id, user.id)
                            db.session.add(new_item)
                        existing_ids.add(dso.id)
                db.session.commit()
                os.remove(path)
                flash(gettext('Session plan uploaded.'), 'form-success')

    session['is_backr'] = True
    return redirect(
        url_for('main_sessionplan.session_plan_schedule',
                session_plan_id=session_plan.id))
示例#4
0
def deepskyobject_search():
    query = request.args.get('q', None)
    if query is None:
        abort(404)
    if query and query.isdigit():
        query = 'NGC' + query
    normalized_name = normalize_dso_name(denormalize_dso_name(query))
    dso = DeepskyObject.query.filter_by(name=normalized_name).first()
    if not dso:
        abort(404)
    return redirect(
        url_for('main_deepskyobject.deepskyobject_info', dso_id=dso.name))
示例#5
0
def observed_list_item_add():
    """Add item to observed list."""
    form = AddToObservedListForm()
    dso_name = normalize_dso_name(form.dso_name.data)
    if request.method == 'POST' and form.validate_on_submit():
        deepsky_object = DeepskyObject.query.filter(DeepskyObject.name==dso_name).first()
        if deepsky_object:
            observed_list = ObservedList.create_get_observed_list_by_user_id(current_user.id)
            dso_id = deepsky_object.master_id if deepsky_object.master_id is not None else deepsky_object.id
            if observed_list.append_deepsky_object(dso_id, current_user.id):
                flash(gettext('Object was added to observed list.'), 'form-success')
            else:
                flash(gettext('Object is already on observed list.'), 'form-info')
        else:
            flash(gettext('Deepsky object not found.'), 'form-error')

    return redirect(url_for('main_observed.observed_list_info'))
示例#6
0
def wish_list_item_add():
    """Add item to wish list."""
    form = AddToWishListForm()
    dso_name = normalize_dso_name(form.dso_name.data)
    if request.method == 'POST' and form.validate_on_submit():
        deepsky_object = DeepskyObject.query.filter(
            DeepskyObject.name == dso_name).first()
        if deepsky_object:
            wish_list = WishList.create_get_wishlist_by_user_id(
                current_user.id)
            if wish_list.append_deepsky_object(deepsky_object.id,
                                               current_user.id):
                flash('Object was added to wishlist.', 'form-success')
            else:
                flash('Object is already on wishlist.', 'form-info')
        else:
            flash('Deepsky object not found.', 'form-error')

    return redirect(url_for('main_wishlist.wish_list_info'))
示例#7
0
def session_plan_item_add(session_plan_id):
    """Add item to session plan."""
    session_plan = SessionPlan.query.filter_by(id=session_plan_id).first()
    _check_session_plan(session_plan)

    deepsky_object = None
    form = AddToSessionPlanForm()
    if request.method == 'POST' and form.validate_on_submit():
        dso_name = normalize_dso_name(form.dso_name.data)
        deepsky_object = DeepskyObject.query.filter(
            DeepskyObject.name == dso_name).first()
    elif request.method == 'GET':
        dso_id = request.args.get('dso_id', None)
        if dso_id is not None:
            deepsky_object = DeepskyObject.query.filter(
                DeepskyObject.id == dso_id).first()

    if deepsky_object:
        if not session_plan.find_dso_by_id(deepsky_object.id):
            user = get_anonymous_user(
            ) if current_user.is_anonymous else current_user
            new_item = session_plan.create_new_session_plan_item(
                deepsky_object.id, user.id)
            db.session.add(new_item)
            db.session.commit()
            flash(gettext('Object was added to session plan.'), 'form-success')
        else:
            flash(gettext('Object is already on session plan.'), 'form-info')

        reorder_by_merid_time(session_plan)
    else:
        flash(gettext('Deepsky object not found.'), 'form-error')

    session['is_backr'] = True

    srow_index = request.args.get('row_index')

    return redirect(
        url_for('main_sessionplan.session_plan_schedule',
                session_plan_id=session_plan_id,
                srow_index=srow_index))
示例#8
0
def normalize_glahn_img(img_src_dir, img_dst_dir):
    files = [f for f in sorted(glob.glob(img_src_dir + '/*.jpg'))]
    ignore_set = set()
    for f in files:
        if _try_copy(f, '_8.jpg', img_dst_dir):
            ignore_set.add(f)
            ignore_set.add(f[:-len('_8.jpg')] + '.jpg')

    for f in files:
        if _try_copy(f, '_14.jpg', img_dst_dir):
            ignore_set.add(f)
            ignore_set.add(f[:-len('_14.jpg')] + '.jpg')

    for f in files:
        if _try_copy(f, '_27.jpg', img_dst_dir):
            ignore_set.add(f)
            ignore_set.add(f[:-len('_27.jpg')] + '.jpg')

    for f in files:
        if _try_copy(f, '-Gruppe.jpg', img_dst_dir):
            ignore_set.add(f)

    for f in files:
        if not f in ignore_set and _has_known_prefix(f):
            base_name = os.path.basename(f)
            idx = base_name.find('_')
            if idx >= 0:
                if _try_copy(f, base_name[idx:], img_dst_dir):
                    ignore_set.add(f)
    for f in files:
        if not f in ignore_set and _has_known_prefix(f):
            base_name = os.path.basename(f)
            if base_name.endswith('.jpg'):
                dso_name = base_name[:-len('.jpg')]
                dso_file_name = normalize_dso_name(dso_name) + '.jpg'
                copyfile(f, os.path.join(img_dst_dir, dso_file_name))
示例#9
0
def save_dso_descriptions(translator, src_path, soup, db_connection, user_8mag,
                          lang_code, cons):
    # exponaty , 'zaujimave_objekty', 'challange_objekty', 'priemerne_objekty', 'asterismy'
    elems = soup.find_all(['a', 'h4', 'div'])
    part = None
    rating = None
    found_objects = []
    cons_order = 0
    for elem in elems:
        if elem.name == 'a':
            if elem.has_attr('id') and elem['id'] in [
                    'exponaty', 'zaujimave_objekty', 'challange_objekty',
                    'priemerne_objekty', 'asterismy'
            ]:
                part = elem['id']
                rating = rating_map[part]
                dso_text = ''
                dso_name = ''
                dso_common_name = ''
                cons_order += 1
                continue
            else:
                continue
        elif not part:
            continue
        if elem.name == 'h4':
            dso_text = ''
            dso_name = ''
            dso_common_name = ''
            if part == 'asterismy':
                dso_name = 'ASTER_' + elem.text.strip()
                found_objects.append({'names': [dso_name]})
            else:
                dso_name = elem.text.strip()
                if '(' in dso_name:
                    if ')' in dso_name:
                        dso_common_name = dso_name[dso_name.index('(') +
                                                   1:dso_name.index(')'
                                                                    )].strip()
                        if '–' in dso_common_name:
                            dso_common_name = dso_common_name[dso_common_name.
                                                              index('–') +
                                                              1:].strip()
                        else:
                            if dso_common_name.startswith('NGC'):
                                dso_common_name = ''
                    dso_name = dso_name[:dso_name.index('(')]
                if dso_name.startswith('Sharpless 2-'):
                    dso_name = 'SH2-' + dso_name[len('Sharpless 2-'):]
                elif dso_name.startswith('Collinder'):
                    dso_name = 'Cr' + dso_name[len('Collinder'):]
                elif dso_name.startswith('Melotte'):
                    dso_name = 'Mel' + dso_name[len('Melotte'):]
                elif dso_name.startswith('Palomar'):
                    dso_name = 'Pal' + dso_name[len('Palomar'):]
                elif dso_name.startswith('Barnard'):
                    dso_name = 'B' + dso_name[len('Barnard'):]
                dso_name = normalize_dso_name(dso_name.strip())
                others = []
                if dso_name == 'Stephanov kvintet':
                    dso_name = 'NGC7318'
                    others = ['NGC7320', 'NGC7319', 'NGC7317']
                elif dso_name.startswith('NGC') and any(
                        x in dso_name for x in ['-', '/', '&', 'A']):
                    if '-' in dso_name:
                        dso_items = dso_name.split('-')
                    elif '/' in dso_name:
                        dso_items = dso_name.split('/')
                    elif '&' in dso_name:
                        dso_items = dso_name.split('&')
                    elif 'A' in dso_name:
                        dso_items = dso_name.split('A')
                        dso_items = dso_items[:-1]
                    dso_name = dso_items[0]
                    if dso_name.endswith('A'):
                        dso_name = dso_name[:-1]
                    if dso_name == 'NGC978':
                        dso_name = 'NGC0978A'
                    dso_name = normalize_dso_name(dso_name)
                    for other in dso_items[1:]:
                        others.append(dso_name[:-len(other)] + other)
                found_objects.append({
                    'names': [dso_name] + others,
                    'rating': rating,
                    'dso_common_name': dso_common_name
                })
        elif elem.name == 'div' and elem.has_attr(
                'class') and 'level4' in elem['class']:
            if dso_name:
                t = None if dso_name.startswith('ASTER_') else translator
                dso_text += extract_div_elem(
                    t, db_connection, src_path, elem,
                    img_name=dso_name) + '\n\n'
                found_objects[-1]['text'] = dso_text

    for m in found_objects:
        if m['names'][0].startswith('ASTER_'):
            vic_cs_name = m['names'][0][len('ASTER_'):].strip()
            vic_catalogue_row = vic_catalogue.get(vic_cs_name, None)
            if vic_catalogue_row:
                vic_id = vic_catalogue_row['Vic#'].strip()
                if len(vic_id) < 2:
                    vic_id = '0' + vic_id
                dso_name = 'VIC' + vic_id
                dso = DeepskyObject.query.filter_by(name=dso_name).first()
                if dso:
                    # update constellation ID since it is missing in vic catalogue
                    dso.constellation_id = cons.id
                    db.session.add(dso)

                    text = m['text'] + '\n'
                    text += '##### 10x50 : ' + vic_catalogue_row.get(
                        '10x50', '') + '\n'
                    text += '##### 15x70 :' + vic_catalogue_row.get(
                        '15x70', '') + '\n'
                    text += '##### 25x100 : ' + vic_catalogue_row.get(
                        '25x100', '') + '\n'

                    rating = vic_catalogue_row['10x50'].find('☆')
                    if rating < 0:
                        rating = 5
                    udd = UserDsoDescription(
                        dso_id=dso.id,
                        user_id=user_8mag.id,
                        rating=rating,
                        lang_code=lang_code,
                        cons_order=cons_order,
                        text=text,
                        common_name=vic_catalogue_row.get('name_cs', ''),
                        create_by=user_8mag.id,
                        update_by=user_8mag.id,
                        create_date=datetime.now(),
                        update_date=datetime.now(),
                    )
                    db.session.add(udd)
                else:
                    print('Deepsky object not found. dso name=' + dso_name)
            else:
                print('VIC object not found. cs name=' + vic_cs_name)
        else:
            for dso_name in m['names']:
                dso = DeepskyObject.query.filter_by(name=m['names'][0]).first()
                if dso:
                    dso_text, apertures_texts = _parse_dso_and_apertures(
                        m['text'])
                    udd = UserDsoDescription(
                        dso_id=dso.id,
                        user_id=user_8mag.id,
                        rating=m['rating'],
                        lang_code=lang_code,
                        cons_order=cons_order,
                        text=dso_text,
                        common_name=m['dso_common_name'],
                        create_by=user_8mag.id,
                        update_by=user_8mag.id,
                        create_date=datetime.now(),
                        update_date=datetime.now(),
                    )
                    db.session.add(udd)

                    for aperture_class, ap_text in apertures_texts.items():
                        apert_descr = UserDsoApertureDescription(
                            dso_id=dso.id,
                            user_id=user_8mag.id,
                            lang_code=lang_code,
                            aperture_class=aperture_class,
                            text=ap_text,
                            create_by=user_8mag.id,
                            update_by=user_8mag.id,
                            create_date=datetime.now(),
                            update_date=datetime.now(),
                        )
                        db.session.add(apert_descr)
                else:
                    print('Deepsky object not found. dso name=' +
                          m['names'][0])
示例#10
0
def deepskyobjects():
    """View deepsky objects."""
    search_form = SearchDsoForm()

    sort_by = request.args.get('sortby')

    ret, page = process_paginated_session_search(
        'dso_search_page', [('dso_search', search_form.q),
                            ('dso_type', search_form.dso_type),
                            ('dso_catal', search_form.catalogue),
                            ('dso_maglim', search_form.maglim),
                            ('items_per_page', search_form.items_per_page)])

    if not ret:
        return redirect(
            url_for('main_deepskyobject.deepskyobjects',
                    page=page,
                    sortby=sort_by))

    per_page = get_items_per_page(search_form.items_per_page)

    offset = (page - 1) * per_page

    dso_query = DeepskyObject.query
    if search_form.q.data:
        dso_query = dso_query.filter(
            DeepskyObject.name.like('%' +
                                    normalize_dso_name(search_form.q.data) +
                                    '%'))

    mag_scale = (8, 16)

    if search_form.dso_type.data and search_form.dso_type.data != 'All':
        dso_query = dso_query.filter(
            DeepskyObject.type == search_form.dso_type.data)

    if search_form.catalogue.data and search_form.catalogue.data != 'All':
        cat_id = Catalogue.get_catalogue_id_by_cat_code(
            search_form.catalogue.data)
        if cat_id:
            dso_query = dso_query.filter_by(catalogue_id=cat_id)

    if not search_form.q.data and search_form.maglim.data is not None and search_form.maglim.data < mag_scale[
            1]:
        dso_query = dso_query.filter(
            DeepskyObject.mag < search_form.maglim.data)

    sort_def = {
        'name': DeepskyObject.name,
        'type': DeepskyObject.type,
        'ra': DeepskyObject.ra,
        'dec': DeepskyObject.dec,
        'constellation': DeepskyObject.constellation_id,
        'mag': DeepskyObject.mag,
    }

    table_sort = create_table_sort(sort_by, sort_def.keys())

    order_by_field = None
    if sort_by:
        desc = sort_by[0] == '-'
        sort_by_name = sort_by[1:] if desc else sort_by
        order_by_field = sort_def.get(sort_by_name)
        if order_by_field and desc:
            order_by_field = order_by_field.desc()

    if order_by_field is None:
        order_by_field = DeepskyObject.id

    shown_dsos = dso_query.order_by(order_by_field).limit(per_page).offset(
        offset).all()

    observed = set()
    if not current_user.is_anonymous:
        for dso in ObservedList.get_observed_dsos_by_user_id(current_user.id):
            observed.add(dso.id)

    pagination = Pagination(page=page,
                            per_page=per_page,
                            total=dso_query.count(),
                            search=False,
                            record_name='deepskyobjects',
                            css_framework='semantic',
                            not_passed_args='back')

    return render_template('main/catalogue/deepskyobjects.html',
                           deepskyobjects=shown_dsos,
                           mag_scale=mag_scale,
                           pagination=pagination,
                           search_form=search_form,
                           table_sort=table_sort,
                           observed=observed)
示例#11
0
 def _get_by_catcode_and_id(self, cat_prefix, dso_id):
     if dso_id <= 0:
         return None
     dso_name = normalize_dso_name(cat_prefix + str(dso_id))
     return DeepskyObject.query.filter_by(name=dso_name).first()