You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

245 lines
7.7 KiB

from flask import Flask, Response, url_for, render_template, Markup, jsonify, redirect, request, flash, session, make_response
from config import Config
import json
import os
import datetime as dt
from datetime import datetime
from pprint import pprint
import re
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from itertools import zip_longest
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)
######################################################################################
# SETTING THE VARIABLES
######################################################################################
# setting variables for holding paths, folder names and the one file for description
path = "static/files/"
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 = []
#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 = []
######################################################################################
#SOME JSON AND WALK OS REALTED THINGIES
######################################################################################
#reading wordlist.json
with open('wordlist.json', 'r', encoding='utf8') as f:
wordlist_dict = json.load(f)
#listing paths and files, not in order but well...
for path, subdirs, files in os.walk(path):
for name in files:
#excluding json files from listing :-)
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:])
#listing the json paths
for path, subdirs, files in os.walk(path):
for name in files:
if name.endswith(".json"):
fullpath = os.path.join(path, name)
jsonfiles.append(fullpath[7:])
fullpathjsonfiles.append(fullpath)
dict = {} #dict for the form entries
with open("static/"+jsonfiles[4], 'r') as f:
data_dict = json.load(f)
datafromjson = data_dict["files"]
######################################################################################
#NOW THE REAL DEAL
######################################################################################
@app.route("/")
def home():
sessionid = "current_user.id"
#add the very first time of connection to the interface
# if veryfirstnow is None :
session['veryfirstnow'] = datetime.now()
return render_template('home.html')
def functionsession():
return(session)
# THIS IS NOT WORKING YET DUNNO WHY
# @app.context_processor
# def context_processor():
# return dict(functionsession=functionsession)
@app.route('/about/')
def about():
return render_template('about.html')
@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)
@app.route('/description')
def description():
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"]
#open json file, list filepaths in array and loop with thefile
textfile=""
with open("static/"+jsonfilefordescription, 'r') as f:
data_dict = json.load(f)
datafromjson = data_dict["files"]
itemid = data_dict["id"]
session["id"].append(itemid)
for file in datafromjson:
if file.lower().endswith(('.html')):
with open("static/"+file,"r", encoding='utf-8') as f:
textfile = f.read()
# wordlinked = "<a href='/diverge?search="+word+"'>"+word+"</a>"
# textfile = re.sub(word, wordlinked, textfile)
textfile = Markup(textfile)
return render_template('description.html', datafromjson=datafromjson, itemid=itemid, textfile=textfile, idno=idno)
@app.route('/diverge', methods=['GET'])
def diverge():
searchterm=request.args.get('search')
now = datetime.now() #description time
session['wordpath'].append(searchterm)
session['clicktime'].append(now)
return render_template('diverge.html', wordlist_dict=wordlist_dict, searchterm=searchterm)
@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)
######################################################################################
#THE SCORE STUFF
######################################################################################
### Add : if score is empty then add some sentence like "your score is empty"
### to be printed to the text document
@app.route("/get-file")
def get_file():
fullscore = None
wordpath = session["wordpath"]
idlist = session["id"]
timelist = session["clicktime"]
veryfirstnow = session['veryfirstnow']
tadam = None
for t in timelist :
t = str(t)
yo = dt.datetime.strptime(t, '%Y-%m-%d %H:%M:%S.%f')
timelistforoperations.append(yo)
prev = None
wholestringy = None
for (word, time, uniqueid) in zip(wordpath,timelistforoperations, idlist):
filler = int(uniqueid)
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
#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)
# 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"
print(tadam)
return Response(tadam,
mimetype="text/plain",
headers={"Content-Disposition":
"attachment;filename=yourveryspecialscore.txt"})
if __name__ == '__main__':
app.run(debug=True)