コード例 #1
0
ファイル: eel_CRA.py プロジェクト: xuexiaogang/Eel
def start_eel(develop):
    """Start Eel with either production or development configuration"""
    if develop:
        directory = 'src'
        app = None
        page = {'port': 3000}
        flags = ['--auto-open-devtools-for-tabs']
    else:
        directory = 'build'
        app = 'chrome-app'
        page = 'index.html'
        flags = []

    eel.init(directory, ['.tsx', '.ts', '.jsx', '.js', '.html'])

    # These will be queued until the first connection is made, but won't be repeated on a page reload
    say_hello_py('Python World!')
    eel.say_hello_js(
        'Python World!'
    )  # Call a JavaScript function (must be after `eel.init()`)

    eel.start(page,
              size=(1280, 800),
              options={
                  'mode': app,
                  'port': 8080,
                  'host': 'localhost',
                  'chromeFlags': flags
              })
コード例 #2
0
ファイル: app.py プロジェクト: kalipy3/Vue-EEL-framework
def start_eel(develop):
    """Start Eel with either production or development configuration."""
    if develop:
        directory = 'src'
        app = None
        page = {'port': 8080}
    else:
        directory = 'web'
        app = 'chrome-app'
        page = 'index.html'

    eel.init(directory)
    say_hello_py("Python World!")
    eel.say_hello_js(
        "Python World!"
    )  # Call a JavaScript function (must be after `eel.init()`)

    eel_kwargs = dict(
        host="localhost",
        port=9000,
        # size=(1280, 800),
    )
    try:
        eel.start(**eel_kwargs)

    except EnvironmentError:
        # If Chrome isn't found, fallback to Microsoft Edge on Win10 or greater
        if sys.platform in ["win32", "win64"
                            ] and int(platform.release()) >= 10:
            eel.start(page, mode="edge", **eel_kwargs)
        else:
            raise
コード例 #3
0
    def start(self):
        """Start Eel"""
        if self.Develop:
            # TODO launch browser
            directory = 'wwwroot'
            app = None
            page = {'port': 3000}
            flags = ['--auto-open-devtools-for-tabs']
        else:
            directory = 'wwwroot'
            #app = 'chrome-app'
            app = None
            page = 'index.html'
            flags = []

        eel.init(directory, ['.tsx', '.ts', '.jsx', '.js', '.html'])

        # These will be queued until the first connection is made, but won't be repeated on a page reload
        #say_hello_py('Python1')
        eel.say_hello_js(
            'Python2'
        )  # Call a JavaScript function (must be after `eel.init()`)

        eel.start(page,
                  size=(1280, 800),
                  options={
                      'mode': app,
                      'port': self.Port,
                      'host': 'localhost',
                      'chromeFlags': flags
                  })
def say_hello_py(query, cutoff, choice):
    global doc_freq
    if vectors == None or weights == None or documentFreq == None or corpus == None or choice == 0:
        eel.say_hello_js("Building Indexes ...")
        choice = 0
    result = entertain(query, cutoff, choice)
    return result
コード例 #5
0
def say_hello_py(query, cutoff, choice):
    global doc_freq
    if doc_freq == None or choice == 0:
        eel.say_hello_js("Building Indexes ...")
        choice = 0
    result = entertain(query, cutoff, choice)
    return result
コード例 #6
0
ファイル: eel_CRA.py プロジェクト: zphiliam/Eel
def start_eel(develop):
    """Start Eel with either production or development configuration."""

    if develop:
        directory = 'src'
        app = None
        page = {'port': 3000}
    else:
        directory = 'build'
        app = 'chrome-app'
        page = 'index.html'

    eel.init(directory, ['.tsx', '.ts', '.jsx', '.js', '.html'])

    # These will be queued until the first connection is made, but won't be repeated on a page reload
    say_hello_py('Python World!')
    eel.say_hello_js(
        'Python World!'
    )  # Call a JavaScript function (must be after `eel.init()`)

    eel_kwargs = dict(
        host='localhost',
        port=8080,
        size=(1280, 800),
    )
    try:
        eel.start(page, mode=app, **eel_kwargs)
    except EnvironmentError:
        # If Chrome isn't found, fallback to Microsoft Edge on Win10 or greater
        if sys.platform in ['win32', 'win64'
                            ] and int(platform.release()) >= 10:
            eel.start(page, mode='edge', **eel_kwargs)
        else:
            raise
コード例 #7
0
ファイル: run.py プロジェクト: NomanAnjum09/KNNandKmean
 def predict_text(self, text):
     if self.corpus == None or self.documentFreq == None or self.weights == None or self.vectors == None:
         eel.say_hello_js("KNN Not Trained Yet!! Please Train First")
         return 0
     prediction = ""
     parsed = parse_Query(text)
     results, query_tf, parsed = process_Query(parsed, self.corpus)
     for i in range(len(results) - 1, -1,
                    -1):  #Remove words from query which are not in corpus
         if (results[i] == -1):
             parsed.pop(i)
             results.pop(i)
             query_tf.pop(i)
     result = fetch_docs(parsed, query_tf, results, self.vectors,
                         self.weights, self.documentFreq, self.corpus)
     docs = []
     for i, arr in self.vectors.items():
         docs.append(i)
     sort_doc(result, docs, 0, len(result) - 1)
     p = []
     for i in range(len(docs) - 1, len(docs) - 4, -1):
         p.append(docs[i].split('.')[0])
     try:
         prediction = statistics.mode(p)
     except:
         prediction = p[len(p) - 1]
     return prediction
コード例 #8
0
def start_eel(develop):
    """Start Eel with either production or development configuration."""
    directory = 'src'
    eel.init(directory)
    say_hello_py('Python World!')
    eel.say_hello_js(
        'Python World!'
    )  # Call a JavaScript function (must be after `eel.init()`)

    eel_kwargs = dict(
        host='localhost',
        port=9000,
        # size=(1280, 800),
    )
    try:
        # eel.start(page, mode=app, **eel_kwargs)
        eel.start(**eel_kwargs)

    except EnvironmentError:
        # If Chrome isn't found, fallback to Microsoft Edge on Win10 or greater
        if sys.platform in ['win32', 'win64'
                            ] and int(platform.release()) >= 10:
            eel.start(page, mode='edge', **eel_kwargs)
        else:
            raise
コード例 #9
0
ファイル: run.py プロジェクト: NomanAnjum09/KNNandKmean
    def run_KNN(self):
        if self.corpus == None or self.documentFreq == None or self.weights == None or self.vectors == None:
            eel.say_hello_js("KNN Not Trained Yet!! Please Train First")
            return
        try:
            file = open('./KNN/testDocs.txt', 'r')
            test = json.load(file)
            file.close()
        except:
            eel.say_hello_js("KNN Not Trained Yet!! Please Train First")
        prediction = []
        test_label = []

        print("Running KNN")
        for label, arr in test.items():
            for filename in arr:
                test_label.append(label)
                file = open(filename, 'r')
                text = file.read()
                file.close()
                parsed = parse_Query(text)
                results, query_tf, parsed = process_Query(parsed, self.corpus)
                for i in range(
                        len(results) - 1, -1,
                        -1):  #Remove words from query which are not in corpus
                    if (results[i] == -1):
                        parsed.pop(i)
                        results.pop(i)
                        query_tf.pop(i)
                result = fetch_docs(parsed, query_tf, results, self.vectors,
                                    self.weights, self.documentFreq,
                                    self.corpus)
                docs = []
                for i, arr in self.vectors.items():
                    docs.append(i)
                sort_doc(result, docs, 0, len(result) - 1)
                p = []
                for i in range(len(docs) - 1, len(docs) - 4, -1):
                    p.append(docs[i].split('.')[0])
                try:
                    prediction.append(statistics.mode(p))
                except:
                    prediction.append(p[len(p) - 1])
        return accuracy_score(test_label, prediction), confusion_matrix(
            test_label, prediction)
コード例 #10
0
def say_hello_py(x):
    """Print message from JavaScript on app initialization, then call a JS function."""
    print('Hello from %s' % x)
    eel.say_hello_js('Python {from within say_hello_py()}!')
コード例 #11
0
ファイル: run-uikit.py プロジェクト: kvamob/cadastron
@eel.expose                         # Expose this function to Javascript
def save_map_image(folder, filename, img_type):
    """
    Сохраняет изображение, помещенное в Clipboard, в файл на диске
    folder - имя папки с отчетом
    filename - имя файла с изображением
    img_type - тип изображения: 'JPEG' или 'PNG'
    """
    dst_path = os.path.join(settings.REPORTS_PATH, folder, 'images')
    print(f'>>> Путь к папке с картинками: {dst_path}')
    if os.path.exists(dst_path):
        img_file = os.path.join(dst_path, filename)
        print(f'save_map_image: файл {img_file} \n')
        time.sleep(1)  # без этой задержки берет из clipboard предыдущее содержимое
        img = ImageGrab.grabclipboard()  # from PIL import ImageGrab
        # eel.addOutput(f'save_map_image: файл {img_file} \n')
        img.save(img_file, img_type)   # img_type: 'JPEG' или 'PNG'
    else:
        print(f'*** save_map_image: папка {dst_path} не существует\n')
        eel.addOutput(f'*** save_map_image: папка {dst_path} не существует\n')
        logging.debug(f'*** save_map_image: папка {dst_path}не существует\n')


eel.print_build_js(f'v {app.version} Build: {app.build}')     # Call a Javascript function
logging.info(f'******************** Starting Cadastron v{app.version} Build: {app.build} ********************')
eel.say_hello_js('connected!')   # Call a Javascript function
eel.print_to_textarea_js('')     # Call a Javascript function

eel.start('main-uikit.html', size=(800, 1050))    # Start
コード例 #12
0
import eel


#暴露给js调用
@eel.expose
def hello_world():
    return "Hello from python"


# 定义html文件所在文件夹名称
eel.init('dist')
#py调用js 必须在eel.init之后调用
eel.say_hello_js("i am py")
# 启动的函数调用放在最后,port=0表示使用随机端口,size=(宽,高)
eel.start('index.html', port=0, size=(600, 300))
コード例 #13
0
ファイル: hello.py プロジェクト: brentvollebregt/Eel
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
コード例 #14
0
import eel

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


@eel.expose
def say_hello_py(x):
    print('Hello from %s' % x)


say_hello_py('Python World!')
eel.say_hello_js('Python World!')

eel.start('helloworld.html', size=(300, 200))
コード例 #15
0
ファイル: server.py プロジェクト: bgamut/eel_example
import eel
import datetime as dt
import json
import subprocess
eel.init('web')


@eel.expose
def getTime():
    now = str(dt.datetime.now())
    #return json.dumps({'now':now})
    return now


#eel.js_random()(print)


def testThread():
    #below should be replaced by an electron app call if necessary.
    #maybe have a json file and regular checks from the javascript side to update values.
    subprocess.call(['touch', 'other.html'])


eel.spawn(testThread)
eel.start('main.html')
random_number_from_javascript = eel.js_random()()
print(random_number_from_javascript)
eel.say_hello_js('javascript')
コード例 #16
0
ファイル: eel_CRA.py プロジェクト: xuexiaogang/Eel
def say_hello_py(x):
    # Print to Python console
    print('Hello from %s' % x)
    # Call a JavaScript function
    eel.say_hello_js('Python {from within say_hello_py()}!')
コード例 #17
0
ファイル: script.py プロジェクト: brentvollebregt/Eel
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
コード例 #18
0
ファイル: run.py プロジェクト: NomanAnjum09/KNNandKmean
def say_hello_py(text, func):
    knn = KNN()
    kmean = Kmeans()

    if func == 'trainKNN':
        eel.say_hello_js("Generating Vectors From 70% Data ...")
        knn.train_KNN()
        eel.say_hello_js("Vectors Generated Successfully")
        time.sleep(1)
        file = open('./KNN/testDocs.txt', 'r')
        test = json.load(file)
        file.close()
        text = "<h3><span style='color:yellow'>Seperated Test Files</span></h3><br/>"
        for key, value in test.items():
            text += "<h5 style='color:#F9008C'>{}</h5 style='color:#00A1F9'><p style='color:yellow'>{}</p>".format(
                key, value)
        return text
    elif func == 'testKNN':
        eel.say_hello_js("Working on 30% Test Data ...")
        accuracy, confusion = knn.run_KNN()
        eel.say_hello_js("Testing Completed. Fetching Results")
        time.sleep(1)
        text = "<div style='color:rgb(137, 202, 211);font-size:large;'>Accuracy Score = {}</div>".format(
            accuracy)
        text += "<div style='color:rgb(137, 202, 211);font-size:large;'>Atual on x, Predicted on y</div>"
        text += "<div style='color:rgb(137, 202, 211);'> At Cr Ft Rg Tn</div>"
        text += "<div style='color:aliceblue;'>{}</div>".format(confusion)
        return text
    elif func == 'predictKNN':
        eel.say_hello_js("Working On Your Document")
        time.sleep(1)
        pred = knn.predict_text(text)
        if pred == 0:
            return
        eel.say_hello_js("Here We Go...")
        text = "<div style='font-size: larger;font-weight: bolder; color:yellow'>Your Document Belongs To {} Class</div>".format(
            pred)
        return text
    elif func == 'trainKmeans':
        eel.say_hello_js1("Generating Vectors For Kmean Clustering")
        kmean.train_Kmean()
        eel.say_hello_js1("Kmeans Vectors Genrated")
        file = open('./Kmean/vector.json')
        fsize = json.load(file)
        file.close()
        for key, value in fsize.items():
            eel.setFeatureSize("Feauture Set Size = {}".format(len(value)))
            break
        return
    elif func == 'testKmeans':
        eel.say_hello_js1("Genrating Clusters Please Wait..")
        param = text.split(',')
        iteration = int(param[0], base=10)
        no_cluster = int(param[1], base=10)
        print(iteration)
        print(no_cluster)
        cluster = kmean.run_K_mean(iteration, no_cluster)
        if cluster == 0:
            eel.say_hello_js1(
                "Kmeans Vectors Not Found. Generate Vectors First")
            return
        eel.say_hello_js1("Here We Go..")
        text = "<div style='color:yellow'>{}</div>".format(cluster)
        return text
    elif func == 'seeList':
        try:
            file = open('./KNN/testDocs.txt', 'r')
            data = json.load(file)
            file.close()
        except:
            eel.say_hello_js("No Data Found. Please Run KNN")
            return
        text = "<h3><span style='color:yellow'>Seperated Test Files</span></h3><br/>"
        for key, value in data.items():
            text += "<h5 style='color:#F9008C'>{}</h5 style='color:#00A1F9'><p style='color:yellow'>{}</p>".format(
                key, value)
        return text
    elif func == 'featureSize':
        try:
            file = open('./Kmean/vector.json')
            fsize = json.load(file)
            file.close()
            for key, value in fsize.items():
                eel.setFeatureSize("Feauture Set Size = {}".format(len(value)))
                break
        except:
            eel.setFeatureSize("Vectors Not Generated Yet")
    elif func == 'seeCluster':
        try:
            file = open('./Kmean/latestCluster.txt', 'r')
            text1 = file.read()
            file.close()
            return text1
        except:
            eel.say_hello_js1("No Clusters Generated Yet")
    elif func == 'predictKMean':
        eel.say_hello_js1("Working On Your Document")
        time.sleep(1)
        pred = kmean.predict_text(text)
        if pred == 0:
            eel.say_hello_js1("Clusters Not Generated Yet")
            return
        eel.say_hello_js1("Here We Go...")
        text = "<div style='font-size: larger;font-weight: bolder; color:yellow'>Your Document Belongs To {} Cluster</div>".format(
            pred)
        return text
コード例 #19
0
    if domain in server.keys():
        return server[domain]
    else:
        ip = None
        prefix = ['mail.', 'smtp.', 'smtp.mail.', 'smtp-mail.']
        for i in prefix:
            try:
                connection = socket.create_connection(
                    (i + complete_domain, 465), timeout=2)
                if connection:
                    ip = i + complete_domain
                    connection.close()
                    return ip
            except:
                pass
            if ip:
                return ip
            else:
                return False


if __name__ == "__main__":
    say_hello_py("Server started.")
    eel.say_hello_js("Server connected.")  # Call a Javascript function

    template = check_if_user_exists()

    eel.start(template, mode="electron")  # Start

    conn.close()
コード例 #20
0
ファイル: input.py プロジェクト: rheehot/learning-code
import eel

eel.init('web')


@eel.expose
def handle_input(x):
    print('%s' % x)


eel.say_hello_js('connected!')

eel.start('input.html', size=(500, 200))
コード例 #21
0
def entertain(text, cutoff, choice):

    parsed = parse_Query(text)
    if (choice == 1):
        print("Using Preprocessed Data")
        pass
    else:
        print("Running From Scratch")  #Run from scratch if flag is on
        tokenizer()
        Processor()

    print(parsed)
    eel.say_hello_js("Processing Query ...")  #Send current status to frontend
    results, query_tf, parsed = process_Query(parsed)

    for i in range(len(results) - 1, -1,
                   -1):  #Remove words from query which are not in corpus
        if (results[i] == -1):
            parsed.pop(i)
            results.pop(i)
            query_tf.pop(i)

    result = fetch_docs(parsed, query_tf, results)
    docs = []
    print("Result Of Cosine Calculation")

    for i in range(56):
        docs.append(i)
    sort_doc(result, docs, 0, len(result) - 1)
    print(list(zip(docs, result)))

    ans = []
    counter = 0
    print("Cutoff", end='->')
    print(float(cutoff))
    for i in range(len(result)):
        real_query = copy.deepcopy(parsed)
        text = ""
        if (result[i] >= float(cutoff)):
            text += "<div style='color:blue'>Doc#{}--{}</div>\n".format(
                docs[i], result[i])
            counter += 1

            #Fetch Summary   ###########This Part Is Extra And is done via python builtin methods
            file = open('./Trump Speechs/speech_{}.txt'.format(docs[i]))
            data = file.read().split('.')
            counter1 = 0
            flag = 0
            for line in data:
                for k in range(len(real_query) - 1, -1, -1):
                    if real_query[k] in line.lower() or lemmatizer.lemmatize(
                            real_query[k]) in line.lower():
                        text += line
                        text += '\n'
                        text += "<div style='color:blue'>                              -----------------------------------</div>"
                        text += '\n'
                        real_query.pop(k)
                        counter1 += 1
                        if (counter1 == 2):
                            flag = 1
                            break
                if (flag == 1):
                    break
            text += "\n\n"
            #ans.append("(doc{}-{})\n".format(docs[i],result[i]))
            ans.append(text)

    ans.reverse()
    print(counter)
    res = "Lenght = {}\n\n".format(counter)
    for a in ans:
        print(a)
        res += a
        res += "<div style='color:magenta'>            ************************************************************</div>\n"
    return res
コード例 #22
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('templates/hello.html', size=(300, 200),
          templates='templates')  # Start
def entertain(text, cutoff, choice):

    global vectors
    global weights
    global documentFreq
    global corpus
    parsed = parse_Query(text)
    if (choice == 1 and vectors != None and weights != None
            and documentFreq != None and corpus != None):
        print("Using Preprocessed Data")
        pass
    else:

        print("Running From Scratch")  #Run from scratch if flag is on
        doc_vocab, doc_freq = tokenizer()
        Processor(doc_vocab, doc_freq)
        file = open('./Data/Corpus.txt', 'r')
        corpus = file.read().split(',')
        file.close()

        file = open('./Data/DocumentFrequency.txt', 'r')
        documentFreq = file.read().split(',')
        file.close()

        file = open('./Data/Weights.txt', 'r')
        weights = file.read().split(',')
        file.close()

        file = open('./Data/Vectors.txt', 'r')
        vectors = json.load(file)
        file.close()

    print(parsed)
    eel.say_hello_js("Processing Query ...")  #Send current status to frontend
    results, query_tf, parsed = process_Query(parsed, corpus)

    for i in range(len(results) - 1, -1,
                   -1):  #Remove words from query which are not in corpus
        if (results[i] == -1):
            parsed.pop(i)
            results.pop(i)
            query_tf.pop(i)

    result = fetch_docs(parsed, query_tf, results, vectors, weights,
                        documentFreq)
    docs = []
    print("Result Of Cosine Calculation")

    for i in range(56):  #print answer and related docs
        docs.append(i)
    sort_doc(result, docs, 0, len(result) - 1)
    print(list(zip(docs, result)))

    ans = []
    counter = 0
    print("Cutoff", end='->')
    print(float(cutoff))
    for i in range(len(result)):
        real_query = copy.deepcopy(parsed)  #Copying Orijinal Query
        text = ""
        if (result[i] >= float(cutoff)):
            text += "<div style='color:blue'>Doc#{}--{}</div>\n".format(
                docs[i], result[i])
            counter += 1

            #Fetch Summary   ###########This Part Is Extra And is done via python builtin methods
            file = open('./Trump Speechs/speech_{}.txt'.format(docs[i]))
            data = file.read().split('.')
            counter1 = 0
            flag = 0
            for line in data:  #Find if query word is in this line
                for k in range(len(real_query) - 1, -1, -1):
                    if real_query[k] in line.lower() or lemmatizer.lemmatize(
                            real_query[k]) in line.lower():
                        text += line
                        text += '\n'
                        text += "<div style='color:blue'>                              -----------------------------------</div>"
                        text += '\n'
                        real_query.pop(k)
                        counter1 += 1
                        if (counter1 == 2):
                            flag = 1
                            break
                if (flag == 1):
                    break
            text += "\n\n"
            #ans.append("(doc{}-{})\n".format(docs[i],result[i]))
            ans.append(text)

    ans.reverse()
    print(counter)
    res = "<div style='color:red;text-decoration:underline'>Lenght = {}\n\n</div>".format(
        counter)
    for a in ans:
        print(a)
        res += a
        res += "<div style='color:magenta'>                 ************************************************************</div>\n"
    return res