<commit_before># coding=utf-8

import json
from operator import itemgetter
import urllib2

from bson import ObjectId
from bson.errors import InvalidId
from flask import Blueprint, request, render_template, make_response, abort

from slideatlas import models, security
from slideatlas.common_utils import jsonify

def jsonifyView(db, viewid, viewobj):
    imgdb = viewobj['ViewerRecords'][0]['Database']
    imgid = viewobj['ViewerRecords'][0]['Image']

    imgobj = db['images'].find_one({'_id': ObjectId(imgid)})

    img = {
        'db': imgdb,
        'viewid': viewid,
        'image': str(imgobj['_id']),
        'origin': imgobj['origin'],
        'spacing': imgobj['spacing'],
        'levels': 1,
        'dimensions': imgobj['dimensions'],
        'TileSize': imgobj.get('TileSize', 256)
    }
    if 'levels' in imgobj:
        img['levels'] = imgobj['levels']

    return jsonify(img)


# view and note are the same in the new schema.
# It becomes so simple!
def glnote(db, viewid, viewobj, edit):
    email = getattr(security.current_user, 'email', '')
    return make_response(render_template('view.html',
                                         view=viewid,
                                         user=email,
                                         edit=edit))



# Flip the y-axis of a view from origin lower left, to origin upper right.
# When this is working well, I will apply it to all views in the database.
def flipAnnotation(annot, paddedHeight):
    if annot["type"] == "text":
        annot["offset"][1] = -annot["offset"][1] - annot["size"]
        annot["position"][1] = paddedHeight - annot["position"][1]
    if annot["type"] == "circle":
        annot["origin"][1] = paddedHeight - annot["origin"][1]
    if annot["type"] == "polyline":
        for point in annot["points"]:
            point[1] = paddedHeight - point[1]
    if annot["type"] == "pencil":
        for shape in annot["shapes"]:
            for point in shape:
                point[1] = paddedHeight - point[1]



def flipViewerRecord(viewerRecord):
    # this is wrong.  It should not be in the databse this way
    paddedHeight = 256 << (viewerRecord["Image"]["levels"] - 1)
    if 'Camera' in viewerRecord:
        viewerRecord["Camera"]["Roll"] = -viewerRecord["Camera"]["Roll"]
        viewerRecord["Camera"]["FocalPoint"][1] = paddedHeight - viewerRecord["Camera"]["FocalPoint"][1]
    if 'Annotations' in viewerRecord:
        for annotation in viewerRecord["Annotations"]:
            flipAnnotation(annotation, paddedHeight)

def convertImageToPixelCoordinateSystem(imageObj):
    # origin ?

    if not imageObj.has_key("bounds"):
        imageObj["bounds"] = [0, imageObj["dimensions"][0], 0, imageObj["dimensions"][1]]

    # Coordinate system defaults to "Pixel" (upper left origin)
    if imageObj.has_key("CoordinateSystem") and imageObj["CoordinateSystem"] == "Photo":
        if imageObj.has_key("bounds"):
            # tile dimension should be stored in image schema
            paddedHeight = 256 << (imageObj["levels"] - 1)
            tmp = imageObj["bounds"][2]
            imageObj["bounds"][2] = paddedHeight-imageObj["bounds"][3]
            imageObj["bounds"][3] = paddedHeight-tmp
            imageObj["CoordinateSystem"] = "Pixel"

def convertViewToPixelCoordinateSystem(viewObj):
    if viewObj.has_key("Children"):
        for child in viewObj["Children"]:
            convertViewToPixelCoordinateSystem(child)
    if viewObj.has_key("CoordinateSystem") and viewObj["CoordinateSystem"] == "Photo":
        for record in viewObj["ViewerRecords"]:
            flipViewerRecord(record)
    viewObj["CoordinateSystem"] = "Pixel"



mod = Blueprint('glviewer', __name__,
                template_folder="templates",
                static_folder="static",
                url_prefix="/webgl-viewer"
                )

@mod.route('')
<EMAIL>
def glview():

    # if a presentation sets the sessid, but not the view,
    # I will create a new presentation object.
    sessid = request.args.get('sess', None)
    # See if the user is requesting a view or session
    viewid = request.args.get('view', None)
    # See if editing will be enabled.
    edit = request.args.get('edit', "false")


    """
    - /glview?view=10239094124&db=507619bb0a3ee10434ae0827
    """
    # Option to load an image from an external server.
    scene = request.args.get('scene', None)
    if scene:
        response = urllib2.urlopen(scene)
        # this is a string
        result = response.read()
        # Take out the quotes that are giving me a pain.
        result = result.replace('"function', 'function')
        result = result.replace('}"', '}')
        # temp fix for a typo in Daniels json.
        result = result.replace("''", "'")
        return make_response(render_template('scene.html', scene = result))

    # get all the metadata to display a view in the webgl viewer.
    ajax = request.args.get('json', None)

    # in the future, the admin database will contain everything except
    # the image data and attachments.
    admindb = models.ImageStore._get_db()
    db = admindb

    viewobj = None
    if viewid:
        viewobj = readViewTree(db, viewid)

    if ajax:
        return jsonifyView(db,viewid,viewobj)

    # default
    email = getattr(security.current_user, 'email', '')
    return make_response(render_template('view.html',
                                         view=viewid,
                                         user=email,
                                         sess=sessid,
                                         edit=edit))




# Query for images.  Avoids all the complications of views.
# we still search views because they have all the meta data.
# the views just vote on which image is most relavant.
@mod.route('/query')
#@security.login_required
def image_query():
    """
    - /query?words=[]
    """
    terms = request.args.get('terms', "").split()
    db = models.ImageStore._get_db()

    # I do not think the $text seach can work on individual fields
    # so I can not weight them separatly.  I would like title<commit_msg>Mongo loading slide show twice.  Mongo is slow.<commit_after># coding=utf-8

import json
from operator import itemgetter
import urllib2

from bson import ObjectId
from bson.errors import InvalidId
from flask import Blueprint, request, render_template, make_response, abort

from slideatlas import models, security
from slideatlas.common_utils import jsonify

def jsonifyView(db, viewid, viewobj):
    imgdb = viewobj['ViewerRecords'][0]['Database']
    imgid = viewobj['ViewerRecords'][0]['Image']

    imgobj = db['images'].find_one({'_id': ObjectId(imgid)})

    img = {
        'db': imgdb,
        'viewid': viewid,
        'image': str(imgobj['_id']),
        'origin': imgobj['origin'],
        'spacing': imgobj['spacing'],
        'levels': 1,
        'dimensions': imgobj['dimensions'],
        'TileSize': imgobj.get('TileSize', 256)
    }
    if 'levels' in imgobj:
        img['levels'] = imgobj['levels']

    return jsonify(img)


# view and note are the same in the new schema.
# It becomes so simple!
def glnote(db, viewid, viewobj, edit):
    email = getattr(security.current_user, 'email', '')
    return make_response(render_template('view.html',
                                         view=viewid,
                                         user=email,
                                         edit=edit))



# Flip the y-axis of a view from origin lower left, to origin upper right.
# When this is working well, I will apply it to all views in the database.
def flipAnnotation(annot, paddedHeight):
    if annot["type"] == "text":
        annot["offset"][1] = -annot["offset"][1] - annot["size"]
        annot["position"][1] = paddedHeight - annot["position"][1]
    if annot["type"] == "circle":
        annot["origin"][1] = paddedHeight - annot["origin"][1]
    if annot["type"] == "polyline":
        for point in annot["points"]:
            point[1] = paddedHeight - point[1]
    if annot["type"] == "pencil":
        for shape in annot["shapes"]:
            for point in shape:
                point[1] = paddedHeight - point[1]



def flipViewerRecord(viewerRecord):
    # this is wrong.  It should not be in the databse this way
    paddedHeight = 256 << (viewerRecord["Image"]["levels"] - 1)
    if 'Camera' in viewerRecord:
        viewerRecord["Camera"]["Roll"] = -viewerRecord["Camera"]["Roll"]
        viewerRecord["Camera"]["FocalPoint"][1] = paddedHeight - viewerRecord["Camera"]["FocalPoint"][1]
    if 'Annotations' in viewerRecord:
        for annotation in viewerRecord["Annotations"]:
            flipAnnotation(annotation, paddedHeight)

def convertImageToPixelCoordinateSystem(imageObj):
    # origin ?

    if not imageObj.has_key("bounds"):
        imageObj["bounds"] = [0, imageObj["dimensions"][0], 0, imageObj["dimensions"][1]]

    # Coordinate system defaults to "Pixel" (upper left origin)
    if imageObj.has_key("CoordinateSystem") and imageObj["CoordinateSystem"] == "Photo":
        if imageObj.has_key("bounds"):
            # tile dimension should be stored in image schema
            paddedHeight = 256 << (imageObj["levels"] - 1)
            tmp = imageObj["bounds"][2]
            imageObj["bounds"][2] = paddedHeight-imageObj["bounds"][3]
            imageObj["bounds"][3] = paddedHeight-tmp
            imageObj["CoordinateSystem"] = "Pixel"

def convertViewToPixelCoordinateSystem(viewObj):
    if viewObj.has_key("Children"):
        for child in viewObj["Children"]:
            convertViewToPixelCoordinateSystem(child)
    if viewObj.has_key("CoordinateSystem") and viewObj["CoordinateSystem"] == "Photo":
        for record in viewObj["ViewerRecords"]:
            flipViewerRecord(record)
    viewObj["CoordinateSystem"] = "Pixel"



mod = Blueprint('glviewer', __name__,
                template_folder="templates",
                static_folder="static",
                url_prefix="/webgl-viewer"
                )

@mod.route('')
<EMAIL>.login_required
def glview():

    # if a presentation sets the sessid, but not the view,
    # I will create a new presentation object.
    sessid = request.args.get('sess', None)
    # See if the user is requesting a view or session
    viewid = request.args.get('view', None)
    # See if editing will be enabled.
    edit = request.args.get('edit', "false")


    """
    - /glview?view=10239094124&db=507619bb0a3ee10434ae0827
    """
    # Option to load an image from an external server.
    scene = request.args.get('scene', None)
    if scene:
        response = urllib2.urlopen(scene)
        # this is a string
        result = response.read()
        # Take out the quotes that are giving me a pain.
        result = result.replace('"function', 'function')
        result = result.replace('}"', '}')
        # temp fix for a typo in Daniels json.
        result = result.replace("''", "'")
        return make_response(render_template('scene.html', scene = result))

    # get all the metadata to display a view in the webgl viewer.
    ajax = request.args.get('json', None)

    # in the future, the admin database will contain everything except
    # the image data and attachments.
    admindb = models.ImageStore._get_db()
    db = admindb

    #viewobj = None
    #if viewid:
    #    viewobj = readViewTree(db, viewid)

    if ajax:
        return jsonifyView(db,viewid,viewobj)

    # default
    email = getattr(security.current_user, 'email', '')
    return make_response(render_template('view.html',
                                         view=viewid,
                                         user=email,
                                         sess=sessid,
                                         edit=edit))




# Query for images.  Avoids all the complications of views.
# we still search views because they have all the meta data.
# the views just vote on which image is most relavant.
@mod.route('/query')
<EMAIL>
def image_query():
    """
    - /query?words=[]
    """
    terms = request.args.get('terms', "").split()
    db = models.ImageStore._get_db()

    # I do not think the $text seach can work on individual fields
    # so I can not weight them separatly.  I would like title
{'fraction_non_alphanumeric': 0.1237729057591623, 'fraction_numerical': 0.010634816753926702, 'mean_word_length': 2.6179343000887836, 'pattern_counts': {'":': 12, '<': 14, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 28, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2056219', 'n_tokens_mistral': 3644, 'n_tokens_neox': 3505, 'n_words': 998}