PushingScores/contextualise.py

331 lines
10 KiB
Python
Raw Normal View History

2019-05-12 06:11:51 +02:00
from flask import Flask, Response, url_for, render_template, Markup, jsonify, redirect, request, flash, session, make_response
2019-04-17 19:31:33 +02:00
from config import Config
import json
import os
2019-05-12 06:11:51 +02:00
import datetime as dt
from datetime import datetime
2019-04-17 19:31:33 +02:00
from pprint import pprint
import re
2019-05-12 06:11:51 +02:00
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from itertools import zip_longest
2019-04-17 19:31:33 +02:00
app = Flask(__name__, static_url_path='', static_folder="static", template_folder="templates")
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
app.config.from_object(Config)
2019-05-12 06:11:51 +02:00
######################################################################################
# SETTING THE VARIABLES
######################################################################################
2019-04-17 19:31:33 +02:00
# setting variables for holding paths, folder names and the one file for description
2019-05-20 16:23:50 +02:00
path = "/static/files/"
2019-04-17 19:31:33 +02:00
jsonfiles = [] #json files
fullpathjsonfiles = [] #fullpath for some situations
listingfiles= [] #fullpaths
listingdirectories = [] #paths
thefile = None #selected file for description
positioninarray = 8 #counter
listofdicts=[] #to be able to import and use json content
datafromjson = []
#test getting json file from id
id = "17"
jsonfilefordescription = "files/"+id+"/"+id+".json"
#arrays with the user path of words and numbers
pathofwords = []
pathofnumbers = []
2019-05-12 06:11:51 +02:00
#VARS FOR THE SESSIONS
app.secret_key = 'your secret'
app.config['SESSION_TYPE'] = 'filesystem'
session = {}
session['wordpath'] = []
session['clicktime'] = []
session['id'] = []
session['veryfirstnow'] = None
#VARS FOR THE SCORES
wordpath = []
idlist = []
timelist = []
timelistforoperations = []
2019-05-20 15:56:54 +02:00
# preparing the index.json file for the navbar
index_dict = {}
2019-05-12 06:11:51 +02:00
######################################################################################
#SOME JSON AND WALK OS REALTED THINGIES
######################################################################################
2019-04-17 19:31:33 +02:00
#reading wordlist.json
with open('wordlist.json', 'r', encoding='utf8') as f:
2019-04-17 19:31:33 +02:00
wordlist_dict = json.load(f)
#listing paths and files, not in order but well...
2019-05-20 16:23:50 +02:00
# for path, subdirs, files in os.walk(path):
# for name in files:
# if not name.endswith(".json") and not name.endswith(".DS_Store"):
# fullpath = os.path.join(path, name)
# listingdirectories.append(path)
# listingfiles.append(fullpath[7:]) #fullpaths minus static/
#
# if name.endswith(".json"):
# fullpath = os.path.join(path, name)
# jsonfiles.append(fullpath[7:])
2019-04-17 19:31:33 +02:00
2019-05-20 15:56:54 +02:00
#listing the json paths simultaneously generating a new index.json for the navbar
for path, subdirs, files in os.walk('./static/files/'):
2019-04-17 19:31:33 +02:00
for name in files:
if name.endswith(".json"):
fullpath = os.path.join(path, name)
2019-05-20 15:56:54 +02:00
jsonfiles.append(fullpath[8:])
2019-04-17 19:31:33 +02:00
fullpathjsonfiles.append(fullpath)
2019-05-20 15:56:54 +02:00
with open (fullpath) as f:
temp_dict = json.load(f)
index_dict[temp_dict["id"]] = temp_dict["title"]
2019-04-17 19:31:33 +02:00
2019-05-20 16:23:50 +02:00
# with open("static/"+jsonfiles[4], 'r') as f:
# data_dict = json.load(f)
# datafromjson = data_dict["files"]
2019-04-17 19:31:33 +02:00
2019-05-12 06:11:51 +02:00
######################################################################################
#NOW THE REAL DEAL
######################################################################################
2019-04-17 19:31:33 +02:00
@app.route("/")
def home():
2019-05-12 06:11:51 +02:00
sessionid = "current_user.id"
2019-05-29 11:54:46 +02:00
2019-05-12 06:11:51 +02:00
#add the very first time of connection to the interface
2019-05-29 11:54:46 +02:00
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
2019-05-27 12:05:42 +02:00
return render_template('home.html', wordlist_dict=wordlist_dict)
2019-05-12 06:11:51 +02:00
def functionsession():
return(session)
# THIS IS NOT WORKING YET DUNNO WHY
2019-05-24 16:59:49 +02:00
@app.context_processor
def context_processor():
functionsession = session['wordpath']
return dict(functionsession=functionsession)
2019-04-17 19:31:33 +02:00
@app.route('/about/')
def about():
2019-05-29 11:54:46 +02:00
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
2019-04-17 19:31:33 +02:00
return render_template('about.html')
2019-05-29 11:54:46 +02:00
# @app.route('/all/')
# def all():
# thefile = listingfiles[positioninarray]
# counter2=0
# return render_template('all.html', file=thefile, listingfiles=listingfiles, jsonfiles=jsonfiles, listofdicts=listofdicts, counter2=counter2)
2019-04-17 19:31:33 +02:00
@app.route('/description')
def description():
2019-05-29 11:54:46 +02:00
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
2019-04-17 19:31:33 +02:00
idno=request.args.get('id')
jsonfilefordescription = "files/"+idno+"/"+idno+".json"
with open("static/"+jsonfilefordescription, 'r') as f:
data_dict = json.load(f)
datafromjson = data_dict["files"]
2019-05-12 06:11:51 +02:00
2019-04-17 19:31:33 +02:00
#open json file, list filepaths in array and loop with thefile
textfile=""
2019-05-13 01:45:35 +02:00
textfiles=[]
2019-04-17 19:31:33 +02:00
with open("static/"+jsonfilefordescription, 'r') as f:
data_dict = json.load(f)
datafromjson = data_dict["files"]
itemid = data_dict["id"]
2019-05-12 06:11:51 +02:00
session["id"].append(itemid)
2019-04-17 19:31:33 +02:00
for file in datafromjson:
if file.lower().endswith(('.html')):
2019-05-25 01:26:28 +02:00
with open("static/"+file,"r", encoding='utf-8') as f:
2019-04-17 19:31:33 +02:00
textfile = f.read()
textfile = Markup(textfile)
2019-05-13 01:45:35 +02:00
textfiles.append(textfile)
2019-05-27 17:32:05 +02:00
return render_template('description.html', datafromjson=datafromjson, itemid=itemid, textfiles=textfiles, idno=idno, index_dict=index_dict)
2019-04-17 19:31:33 +02:00
@app.route('/diverge', methods=['GET'])
def diverge():
2019-05-29 11:54:46 +02:00
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
2019-04-17 19:31:33 +02:00
searchterm=request.args.get('search')
2019-05-12 06:11:51 +02:00
now = datetime.now() #description time
session['wordpath'].append(searchterm)
session['clicktime'].append(now)
2019-05-28 15:45:45 +02:00
return render_template('diverge.html', wordlist_dict=wordlist_dict, searchterm=searchterm, index_dict=index_dict)
2019-04-17 19:31:33 +02:00
2019-05-29 11:54:46 +02:00
# @app.route('/listofwords')
# def listofwords():
# # r = jsonify(session)
# r = str(session)
# r0w = session["wordpath"][0]
# r0c = session["clicktime"][0]
# r0id = session["id"][0]
# return render_template('listofwords.html', r=r, r0c=r0c, r0w=r0w, r0id=r0id)
2019-05-12 06:11:51 +02:00
######################################################################################
#THE SCORE STUFF
######################################################################################
### Add : if score is empty then add some sentence like "your score is empty"
### to be printed to the text document
2019-05-12 06:11:51 +02:00
@app.route("/get-file")
def get_file():
2019-05-29 11:54:46 +02:00
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
2019-05-12 06:11:51 +02:00
fullscore = None
wordpath = session["wordpath"]
idlist = session["id"]
timelist = session["clicktime"]
veryfirstnow = session['veryfirstnow']
2019-05-24 16:59:49 +02:00
clickongetfiletime = datetime.now()
2019-05-29 11:54:46 +02:00
tadam = None
2019-05-24 16:59:49 +02:00
initialtime = None
if not (timelist[0] is None):
thetime = timelist[0]
thetime = str(thetime)
thetime = dt.datetime.strptime(thetime, '%Y-%m-%d %H:%M:%S.%f')
initialtime = thetime - veryfirstnow
initialtime = initialtime.total_seconds()
initialtime = int(initialtime)
initialtime = "."*initialtime
print(initialtime)
2019-05-12 06:11:51 +02:00
2019-05-13 01:45:35 +02:00
for t in timelist :
2019-05-12 06:11:51 +02:00
t = str(t)
yo = dt.datetime.strptime(t, '%Y-%m-%d %H:%M:%S.%f')
timelistforoperations.append(yo)
prev = None
wholestringy = None
2019-05-25 01:26:28 +02:00
# print("veryfirstnow : "+str(veryfirstnow)+"\n")
2019-05-24 16:59:49 +02:00
2019-05-29 11:54:46 +02:00
print(wordpath)
print(timelistforoperations)
print(idlist)
2019-05-24 16:59:49 +02:00
2019-05-29 11:54:46 +02:00
for (word, time) in zip(wordpath,timelistforoperations):
# for (word, time, uniqueid) in zip(wordpath,timelistforoperations, idlist):
2019-05-25 01:26:28 +02:00
# print("word : "+word+"\n")
# print("timeofclick : "+str(time)+"\n")
# print("============")
# print(wordpath)
# print("============")
2019-05-29 11:54:46 +02:00
# filler = int(uniqueid)
2019-05-12 06:11:51 +02:00
upperword = word.upper()
#get previous time for substraction
if not (prev is None):
difftime = time - prev
difftime = difftime.total_seconds()
difftime = int(difftime)
# print(difftime)
else:
yo = str(veryfirstnow)
yoyo = dt.datetime.strptime(yo, '%Y-%m-%d %H:%M:%S.%f')
difftime = time - yoyo
difftime = difftime.total_seconds()
difftime = int(difftime)
test = difftime
prev = time
diffpattern = test * '.'
stringy = diffpattern + upperword
if not (wholestringy is None):
wholestringy = wholestringy+stringy
fullscore = wholestringy
else:
wholestringy = upperword
fullscore = wholestringy
2019-05-24 16:59:49 +02:00
# #If fullscore length superior 60 characters, insert linebreak
# # Defining splitting point
# n = 60
# # Using list comprehension
# out = [(fullscore[i:i+n]) for i in range(0, len(fullscore), n)]
# #joining the strings with linebreaks
# tadam = '\n'.join(out)
2019-05-12 06:11:51 +02:00
2019-05-24 16:59:49 +02:00
if not (fullscore is None):
# outside of the loop calculate seconds from "clickongetfiletime" minus the last "time" from the loop
lastdifftime = clickongetfiletime - prev
lastdifftime = lastdifftime.total_seconds()
lastdifftime = int(lastdifftime)
lastdifftime = lastdifftime * '.'
#the 60 seconds thing
# print(lastdifftime+"\n")
fullscore = initialtime+fullscore+lastdifftime
2019-05-13 01:45:35 +02:00
# Defining splitting point
2019-05-12 06:11:51 +02:00
n = 60
2019-05-13 01:45:35 +02:00
# Using list comprehension
2019-05-12 06:11:51 +02:00
out = [(fullscore[i:i+n]) for i in range(0, len(fullscore), n)]
#joining the strings with linebreaks
2019-05-13 01:45:35 +02:00
tadam = '\n'.join(out)
2019-05-24 16:59:49 +02:00
# have a message in file if no nav has been recorded so it's less dull than error page
if tadam is None:
tadam = "This score is Null"
2019-05-12 06:11:51 +02:00
2019-05-24 16:59:49 +02:00
# print("verylastnow : "+str(clickongetfilefime)+"\n")
2019-05-29 11:54:46 +02:00
uniquename = str(clickongetfiletime)
with open('scores/'+uniquename+'.txt', 'a+') as f:
f.write(tadam)
print(tadam)
2019-05-12 06:11:51 +02:00
return Response(tadam,
mimetype="text/plain",
headers={"Content-Disposition":
"attachment;filename=yourveryspecialscore.txt"})
2019-04-17 19:31:33 +02:00
2019-05-27 17:32:05 +02:00
######################################################################################
#INDEX PAGE
######################################################################################
@app.route("/index")
def index():
return render_template('theindex.html', wordlist_dict=wordlist_dict, index_dict=index_dict)
2019-04-17 19:31:33 +02:00
if __name__ == '__main__':
app.run(debug=True)