Beispiel #1
0
    json.dump(generate, open('generate.json', 'w'), indent=4)
    json.dump(settings, open('settings.json', 'w'), indent=4)
    name = main()

    # Move the files up one folder
    p = os.listdir()
    # Get all files to move
    for file in p:
        if str(file).endswith('.town.json') or str(file).endswith('.html'):
            shutil.copyfile(file, os.path.join('web', file))
        elif str(file) == 'beasts' and os.path.isdir(file):
            try:
                os.mkdir(os.path.join('web', 'beasts'))
            except FileExistsError as e:
                print("Beasts folder already exists.")
            for bestiary in os.listdir(file):
                shutil.copyfile(
                    os.path.join('beasts', bestiary),
                    os.path.join(os.path.join('web', 'beasts'), bestiary))

    # Display to GUI
    eel.town_name_js(name)


if __name__ == '__main__':
    # Set web files folder
    eel.init('web')

    # start
    eel.start('index.htm', size=(865, 750))
Beispiel #2
0
           level="DEBUG",
           rotation="1 weeks",
           compression='zip')


@eel.expose
def wrapper(search, count):
    logger.info('Start searching')
    return get_doc(search, count)


@eel.expose
def save_proxy(new_proxy: str, path: str = 'setting.txt') -> bool:
    if status := ((new_proxy :=
                   new_proxy.replace('	', '').replace(' ', '')).replace(
                       '.', '').replace(':', '').isdigit()):
        logger.info(f'Proxy Editing => {new_proxy=}')
        with open(path, 'r+') as outfile:
            file = outfile.readlines()
            outfile.seek(0)
            file[2] = f'proxy={new_proxy}'
            outfile.writelines(file)
            outfile.truncate()
    else:
        logger.error('Invalid proxy format')
    return status


eel.init('web')
eel.start('main.html', size=(2000, 1000))
Beispiel #3
0
import io
import pyqrcode
from base64 import b64encode
import eel

eel.init('web')


@eel.expose
def generate_qr(data):
    img = pyqrcode.create(data)
    buffers = io.BytesIO()
    img.png(buffers, scale=8)
    encoded = b64encode(buffers.getvalue()).decode("ascii")
    print("QR code generation successful.")
    return "data:image/png;base64, " + encoded


eel.start('index.html', size=(600, 600))
    # send SIGTERM
    for p in procs:
        p.terminate()
    gone, alive = psutil.wait_procs(procs, timeout=timeout, callback=on_terminate)
    if alive:
        # send SIGKILL
        for p in alive:
            # print("process {} survived SIGTERM; trying SIGKILL" % p.pid)
            p.kill()
        gone, alive = psutil.wait_procs(alive, timeout=timeout, callback=on_terminate)
        if alive:
            # give up
            for p in alive:
                print("process {} survived SIGKILL; giving up" % p.pid)

@eel.expose
def stop_manager():
    print("Shutting manager down.")
    player_plain.reap(psutil.Process())
    procs = psutil.Process().kill()


print("=== Ready! ===")
print("To play games open http://localhost:6147/run.html in your browser on Mac/Linux/WindowsPro, or http://192.168.99.100:6147/run.html on Windows10Home.")
lock = threading.Lock()

eel.start('run.html', options=options, block=False)

while True:
    eel.sleep(1.0)
Beispiel #5
0
    while True:
        ret, frame = cap.read()
        if ret:
            encoded_frame = cv2.imencode('.jpg', frame)[1]
            base64_data = base64.b64encode(encoded_frame)
            data_string = base64_data.decode()
            frame_string = f'data:image/jpeg;base64,{data_string}'
            try:
                status = eel.jsUploadImage(index, frame_string)()
                if not status:
                    break
            except:
                break
    cap.release()
    print('closing camera')


@eel.expose  # Expose this function to Javascript
def say_hello_py(x):
    print('Hello from %s' % x)


@eel.expose
def start():
    eel.jsCreateCameraLayout(0)


try:
    eel.start('index.html', mode=None)
except Exception as e:
    print(e)
Beispiel #6
0
import eel, os, random

eel.init('web')

@eel.expose
def pick_file(folder):
    if os.path.isdir(folder):
        return random.choice(os.listdir(folder))
    else:
        return 'Not valid folder'

eel.start('file_access.html', size=(320, 120))
Beispiel #7
0
        #s = random.choice(train_set)
        s = {
            'num': 00,
            'len': len(s),
            'raw': text,
            'tokens': tokenize(text),
            'tags': []
        }
        print("phrase: ", s["num"])
        s["decoded"] = decode(s, model)
        res += s["decoded"]
        tok += s["tokens"]

    print(tok)
    print(res)

    eel.SendRes(tok, res)


""" 

        eel.SendRes(s["tokens"],s["decoded"])
   for i in range(0,s["len"]):
        if s["tokens"][i] in model["forget_words"]:
            print("*UNK*\t",s["tokens"][i],"\t",s["tags"][i],"\t",s["decoded"][i])
        else:
            print("     \t",s["tokens"][i],"\t",s["tags"][i],"\t",s["decoded"][i])
"""

eel.start('UIMaterialize.html', mode='chrome', size=(500, 500))
        "金門縣": "F-D0047-085",
    }

    url = f"https://opendata.cwb.gov.tw/api/v1/rest/datastore/{_location_names[location]}?Authorization=CWB-CAABE1A5-C070-40E4-B84C-DD387602B85B&format=JSON&locationName={District}&elementName={element}"
    text = requests.get(url).text
    result = json.loads(requests.get(url).text)

    # take out part of information we want
    result = result["records"]["locations"][0]["location"][0]['weatherElement'][0]['time']
    # Transfer it into DF
    result = pd.DataFrame(result)
    # take out the element value of it
    result['value'] = result['elementValue'].apply(lambda x: x[0]['value'])
    result.drop('elementValue', axis=1)

    if 'startTime' in result.columns:
        result_part1 = result[['startTime','value']]
        result_part2 = result[['endTime','value']].rename(columns={'endTime':'startTime'})
        result = result_part1.append(result_part2,ignore_index=True).sort_values(by=['startTime'])
        result.drop_duplicates(subset='startTime',inplace=True)
        time = result['startTime'].tolist()
     

    elif 'dataTime' in result.columns:
        time = result['dataTime'].tolist()
    value = result['value'].tolist()
    
    return ([time,value])

eel.start('main.html',size = (1000,800))
Beispiel #9
0
import eel
eel.init('web', allowed_extensions=['.js', '.html'])


@eel.expose
def add_py(a, b):

    return a + b


@eel.expose
def substract(a, b):
    return a - b


@eel.expose
def divise(a, b):
    return a / b


@eel.expose
def multiply(a, b):
    return a * b


eel.start('index.html', mode="chrome", size=(770, 580))
Beispiel #10
0
@eel.expose
def get_words():
    ddata = deckapp.get_due_cards()
    print("{} words selected".format(len(ddata)))
    deckapp.ddata = ddata
    data = selectwords(ddata)
    a = io.StringIO()
    json.dump(data, a, separators=(',', ':'))
    return a.getvalue()


@eel.expose
def save_words(deck):
    for a in deck:
        for d in deckapp.ddata:
            if a["sound"] == d.question:
                d.num = a["num"]
    deckapp.save_words(deckapp.ddata)
    return 1


try:
    eel.start('flipbook.html', size=(320, 470), close_callback=handle_exit)
except (SystemExit, MemoryError, KeyboardInterrupt):
    # We can do something here if needed
    # But if we don't catch these safely, the script will crash
    pass

print('This is printed when the window is closed!')
Beispiel #11
0
import eel
import os
import sys
import pandas as pd



#select folder
eel.init('startbootstrap')


@eel.expose
def get_data(filename):
    file = str(os.path.dirname(os.path.realpath(sys.argv[0]))+"/data/"+filename)
    df = pd.read_csv(file)
    
    time = df['time'].tolist()
    x = df['x'].tolist()
    y = df['y'].tolist()
    z = df['z'].tolist()
 
    return time,x,y,z

eel.sel()(get_data)

eel.start('charts.html',size=(1200,800))
            attendance()


@eel.expose
def save_excel(data):
    if os.path.exists(os.path.join(whconfig["excel_location"], whconfig["excel_name"])):
        wb = xl.load_workbook(
            os.path.join(whconfig["excel_location"], whconfig["excel_name"])
        )
        ws = wb.active
    else:
        wb = xl.Workbook()
        ws = wb.active
    col = ws.max_column + 1
    print(data)
    for i in range(1, len(data) + 1):
        ws.cell(row=i, column=col).value = data[i - 1]
    wb.save(os.path.join(whconfig["excel_location"], whconfig["excel_name"]))
    wb.close()
    return


if not os.path.exists(os.path.join(whconfig["driver_path"])):
    os.mkdir(os.path.join(whconfig["driver_path"]))
eel.start(
    "index.html",
    size=(650, 612),
    render_template="jinja",
    cmdline_args=["--disable-dev-tools"],
)
Beispiel #13
0
import eel

eel.init('web')                     # Give folder containing web files

@eel.expose                         # Expose this function to Javascript
def handleinput(x):
    print('%s' % x)

eel.say_hello_js('connected!')   # Call a Javascript function

eel.start('main.html', size=(500, 200))    # Start
Beispiel #14
0
from __future__ import print_function
import eel
import random

eel.init('web')

@eel.expose
def py_random():
    return random.random()

def print_num(n):
    print('Got this from Javascript:', n)

# Call Javascript function, and pass explicit callback function    
eel.js_random()(print_num)

# Do the same with an inline callback
eel.js_random()(lambda n: print('Got this from Javascript:', n))

eel.start('callbacks.html', size=(400, 300))
Beispiel #15
0
def solve_chain():
    print('Solving chain')
    try:
        result = current_chain.get_availability()

        return (round(result, 8), True)

    except Exception as e:
        return (str(e), False)


def search_node(nodeid):
    print(current_chain.chainid)
    for node in current_chain.nodes:
        if node.nodeid == nodeid:
            return node

    return False


def search_block(blockid):
    for block in persistent_data['rbd'].blocks:
        if block.blockid == blockid:
            return block

    return False


if __name__ == "__main__":
    eel.start('index.html', options={'port': 8686})
Beispiel #16
0
@eel.expose
def getResult(query):
    #print(query)
    query = query.strip().lower()
    if query == "":
        return {"resultNews": [], "correctedQuery":'', "resultLen": 0, "searchTime": 0.000}
    correctQuery = SearchAndRank.correctKeywords([query])[0]
    print(correctQuery)
    iniQueryWords = wordsCut.sentence_seg(correctQuery)
    queryWords = []
    for word in iniQueryWords:
        if word != ' ':
            queryWords.append(word)
    SearchResult = SearchAndRank.Search(query,correctQuery,queryWords)
    #print(SearchResult)
    return SearchResult


web_app_options = {
    'mode': '',
    'host': 'localhost',
    'port': 8000,
    'chromeFlags': []
}


if __name__ == '__main__':
    eel.init('front')
    eel.start('index.html', options=web_app_options)
Beispiel #17
0
import eel

eel.init('web')                     # Give folder containing web files

@eel.expose                         # Expose this function to Javascript
def say_hello_py(x):
    print('Hello from %s' % x)

say_hello_py('Python World!')
eel.say_hello_js('Python World!')   # Call a Javascript function

eel.start('hello.html', size=(300, 200))    # Start
import eel
import glob
import io
import json
import os
import platform
import shutil


eel.init('web') #allowed_extensions=[".js",".html"]
eel.start('App/index.html', port=8000)
Beispiel #19
0
            keywords = page.keywords 
            url = page.url
            k = ''
            for key in elem['keys']: 
                k += key + ', ' 
        except: 
            title = ''
            description = ''
            keywords = '' 
            url = page.url
            k = ''
            for key in elem['keys']: 
                k += key + ', '
        mas_excel.append({ 'key': k, 'url': url, 'title': title, 'desc': description, 'keywords': keywords, })

    wb = openpyxl.Workbook()
    sheet = wb.active

    for row, product in enumerate(mas_excel): 
        for col, key in enumerate(product.keys()): 
            cell = sheet.cell(row=row+1, column=col+1) 
            cell.value = product[key]

    
    wb.save("Отчет meta.xlsx")
    return "Отчет готов" 

eel.init('web')
eel.start('main.html', size=(700, 700))

# notify function for windows
elif current_os.lower() == "windows":
    import win10toast as wtt

    toaster = wtt.ToastNotifier()

    @eel.expose
    def notify(msg, head, icon_file=jarvis_icon, ul=1, duration=5):
        toaster.show_toast(head,
                           msg,
                           icon_path=icon_file,
                           threaded=True,
                           duration=duration)


# publish a mqtt message


@eel.expose
def msg_pub(topic, msg, broker=BROKER, port=PORT):
    mqtt.publish.single(topic, hostname=broker, port=port)


if __name__ == "__main__":
    # initialise app on start
    eel.init(static_dir)
    eel.start("index.html", size=SIZE)
    conn.close()
    conn_temp.close()
Beispiel #21
0
import eel
from fht import visualize
import tkinter as tk
from tkinter import filedialog
import os
import inspect

eel.init('web')


@eel.expose
def analyse_file(file, offset):
    return visualize.run_fht(file, offset)


@eel.expose
def select_file():
    root = tk.Tk()
    root.withdraw()
    root.wm_attributes("-topmost", 1)
    file_path = filedialog.askopenfile(title="Selecionar arquivo")
    print(file_path.name)
    return file_path.name


eel.start('main.html', size=(900, 600))
Beispiel #22
0
import task_manager as tM
import eel

eel.init('front', allowed_extensions=['.js', '.html'])


@eel.expose
def createTask(name, **params):
    tM.addTask(name, **params)
    print(f"Tache '{name}' créée avec success.")


@eel.expose
def showTasks():
    tasks = tM.getTasks()
    tasks = tasks[1:]
    for task in tasks:
        eel.addTaskElement(task)


eel.start('index.html', geometry={
    'size': (200, 100),
    'position': (300, 50)
})  # Start (this blocks and enters loop)
Beispiel #23
0
import eel
import core

eel.init('web')


@eel.expose
def ans(a):
    eel.result(core.thickness(int(a)))


eel.start('index.html', size=(800, 900))
Beispiel #24
0
import eel

eel.init("web")


@eel.expose
def updateNote(note):
    noteFile = open("notes.txt", "w+")
    noteFile.write(note)
    noteFile.read()
    noteFile.close()
    return "Note Added"


@eel.expose
def fetchNote(message):
    noteFile = open("notes.txt", "r+")
    notes = noteFile.read()
    print(message)
    return notes


eel.start("index.html")
Beispiel #25
0
def gui():
    eel.init('web')
    eel.start('main.html', size=(350, 350), position=(1540, 30))
Beispiel #26
0
    listener.start()
    return getNextLevel()

@eel.expose
def getNextLevel():
    global current_index
    current_index += 1
    current_shortcut = shortcut_list[current_index]
    return current_shortcut.getDescription()

@eel.expose
def getEncyclopedia():
    list_shortcuts = shortcutdatabase.getAllShortcutsString()
    shortcut_keys = []
    shortcut_descriptions = []
    for i in list_shortcuts:
        items = i.split("=")
        shortcut_keys.append(items[0])
        shortcut_descriptions.append(items[1])

    return [shortcut_keys, shortcut_descriptions]


@eel.expose
def startLevels():
    level_listener = LevelListener('user_output_levels.txt', level)
    level_listener.start()


eel.start('index.html')
Beispiel #27
0
        for post_name in post_name_list:
            path = hexo_path + '/source/_posts/' + post_name
            if os.path.splitext(path)[-1] == '.md':
                posts.append(Post(post_name))
        content = ''
        posts.sort(key=lambda x: x.date, reverse=True)
        for post in posts:
            content += mdui.build({
                'name': 'post/item',
                'date': post.date,
                'tags': post.tags,
                'title': post.title,
                'filename': post.filename,
                'categories': post.categories,
            })
        eel.set_content(
            mdui.get('post/panel').replace('{{ content }}', content))
        eel.active_panel()


@eel.expose
def init():
    global config, hexo_path
    config = yaml.load(read_file(os.getcwd() + '/config.yml'))
    config['hexo'] = yaml.load(read_file(config['hexo-path'] + '_config.yml'))
    hexo_path = os.path.abspath(config['hexo-path'])
    return config


eel.start('index.html', size=(1200, 800))
Beispiel #28
0
import eel

# Set web files folder and optionally specify which file types to check for eel.expose()
eel.init('web', allowed_extensions=['.js', '.html'])

@eel.expose                         # Expose this function to Javascript
def say_hello_py(x):
    print('Hello from %s' % x)

say_hello_py('Python World!')
eel.say_hello_js('Python World!')   # Call a Javascript function

eel.start('hello.html', size=(300, 200))    # Start
Beispiel #29
0
    contract = session.query(Contract).filter_by(
        agent_id=agent_id, number=contract_old_number).first()

    contract.number = contract_new_number
    contract.description = description
    contract.contract_sum = contract_sum
    contract.date_of_conclusion = date_of_conclusion
    contract.date_of_start = date_of_start.strftime('%d.%m.%Y')
    contract.date_of_end = date_of_end.strftime('%d.%m.%Y')
    contract.validity = validity
    contract.days_passed = days_passed
    contract.days_left = days_left
    # contract.state = state

    session.commit()

    global agent_from_all_agents_list

    agent = session.query(Agent).filter_by(id=agent_id).first()
    agent_from_all_agents_list['contracts'] = refresh_contracts_list(agent)

    eel.redirect_to_agent_detail_page()


# create_tables()
# delete_all_tables()
# from_python()

if __name__ == '__main__':
    eel.start('index.html', size=(1400, 700))
Beispiel #30
0
import eel
eel.init('src')

@eel.expose
def exx(x):
    print(x)

eel.start("cook.html", size = (634, 951))
Beispiel #31
0
# to return lists of data
originCities = []
destCities = []
carriers = []
# list for most successful flights
bestFlights = []

# - get list of origin cities, destination cites, and carriers to load select in front end
# - get the best flights determined by pre-selected data:
#   1 - if the success rate is > 90%
#   2 - if the month has the highest success rate
#   3 - if the flight has more than 20 seats available
#   4 - if the origin city is Charlotte, NC
for flight in flightData:
    if (flight["SUCCESSFULNESS"] >= float(90)) & (int(flight["MONTH"]) == int(statistics.mode(maxList))) & (flight["SEATS_AVAIL"] > 20) & (flight["ORIGIN_CITY_NAME"] == "Charlotte, NC"):
        bestFlights.append(flight)
    newOgCity = flight["ORIGIN_CITY_NAME"]
    destCity = flight["DEST_CITY_NAME"]
    carrier = flight["CARRIER_NAME"]
    originCities.append(newOgCity)
    destCities.append(destCity)
    carriers.append(carrier)

# remove duplicates from lists
originCities = list(dict.fromkeys(originCities))
destCities = list(dict.fromkeys(destCities))
carriers = list(dict.fromkeys(carriers))

# start the server
eel.start('main.html')
import eel, random

eel.init('web')

@eel.expose
def py_random():
    return random.random()

def print_num(n):
    print('Got this from Javascript:', n)

# Call Javascript function, and pass explicit callback function    
eel.js_random()(print_num)

# Do the same with an inline callback
eel.js_random()(lambda n: print('Got this from Javascript:', n))

eel.start('callbacks.html', size=(400, 300))
Beispiel #33
0
# Import the eel and random libraries

import eel
import random
from random import choice

# Starts the GUI frontend server

eel.init('web-gui')

eel.start('index.html', size=(1440, 900))

# This function randomly chooses an answer of yes or no


@eel.expose  # Exposes this function (makes it callable) from Javascript
def mainFunction():
    output = (random.choice(['Yes', 'No']))
    if output == 'Yes':
        eel.yesFunction()  # Calls yesFunction() in JavaScript
    else:
        eel.noFunction()  # Calls noFunction() in JavaScript


# For dev purposes only:

while True:
    eel.sleep(10)
Beispiel #34
0
import io
import pyqrcode
from base64 import b64encode
import eel
import requests
eel.init('web')


@eel.expose
def dll(dt,f,to):
    base_url = 'https://api.exchangeratesapi.io/latest'
    url = base_url + '?base=' + f + '&symbols=' + to
    response = requests.get(url)
    if (response.ok is False):
        return "invalid request"
    else:
        data = response.json()
        total = int(dt)*data['rates'][to]
        return total



eel.start('currency.html', size=(600, 600))
Beispiel #35
0
    for p in procs:
        print("Killing ", p.pid)
        p.terminate()
    gone, alive = psutil.wait_procs(procs, timeout=timeout, callback=on_terminate)
    if alive:
        # send SIGKILL
        for p in alive:
            print("process {} survived SIGTERM; trying SIGKILL" % p.pid)
            p.kill()
        gone, alive = psutil.wait_procs(alive, timeout=timeout, callback=on_terminate)
        if alive:
            # give up
            for p in alive:
                print("process {} survived SIGKILL; giving up" % p.pid)

@eel.expose
def stop_manager():
    print("Shutting manager down.")
    player_plain.reap(psutil.Process())
    procs = psutil.Process().kill()


print("=== Ready! ===")
print("To play games open http://localhost:6147/run.html in your browser on Mac/Linux/WindowsPro, or http://192.168.99.100:6147/run.html on Windows10Home.")
lock = threading.Lock()

eel.start('run.html', options=options, block=False)

while True:
    eel.sleep(1.0)
Beispiel #36
0
import eel
from sender import Sender
from request import Http
from response import Response
from header import Header

#!/usr/bin/env python
import socket

import ssl
from http_parser.http import HttpStream
from http_parser.reader import SocketReader

@eel.expose
def submit(d):
    header = Header(d["method"], d["path"], d["httpversion"])
    for i in d['headers']:
        header.add_header(i['header_name'], i['header_value'])
    header.build_from_text()
    print(header.payload)
    s = Sender()
    r = Response()
    resp = r.input_text(s.send(d["protocol"], d["hostname"], header.payload))
    return resp

eel.init('web')
eel.start('index.html')