text
stringlengths 0
5.92k
|
|---|
from taipy.gui import Gui from math import cos, exp value = 10 page = """ Markdown # Taipy *Demo* Value: <|{value}|text|> <|{value}|slider|> <|{compute_data(value)}|chart|> """ def compute_data(decay: int) -> list: return [cos(i / 6) * exp(-i * decay / 600) for i in range(100)] Gui(page).run(use_reloader=True, port=5003)
|
import pymongo from dotenv import load_dotenv import os from taipy.gui import notify import pandas as pd load_dotenv() client = pymongo.MongoClient(os.getenv("MONGO_URI")) db = client["GoShop"] collection_product = db["products"] def insert_one_collection(document): return collection_product.insert_one(document) def all_prodcuts(): cursor = collection_product.find() list_cur = list(cursor) df = pd.DataFrame(list_cur) return df
|
from taipy.gui import Gui, Markdown, navigate from pages.addproduct import addproduct_md from pages.home import home_md from pages.developer import developer_md favicone = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcStQrffFMV3jCG2wB7o7Bs1VwUJ3Z0sWQhbzA&usqp=CAU" # root_md = "<|menu|label=Menu|lov={[('home', Icon('https://static.vecteezy.com/system/resources/thumbnails/000/616/494/small/home-06.jpg','home')), ('addproduct', 'addproduct')]}|on_action=on_menu|>" def on_menu(state, action, info): page = info["args"][0] navigate(state, to=page) pages = { "/": "<center><|navbar|></center>", "home": home_md, "addproduct": addproduct_md, "team": developer_md, } Gui(pages=pages).run(title="Rapid~Receipt", favicon=favicone, run_browser=False, use_reloader=True, port=5555)
|
from taipy.gui import Markdown, notify from database import all_prodcuts import pandas products = all_prodcuts() del products["_id"] products["isavailable"].replace({True: "Yes", False: "No"}) yes = 0 no = 0 for i in products["isavailable"]: if i == True: yes = yes+1 else: no = no+1 data = { "Country": ["Sold", "Available"], "Area": [yes, no] } # for count vs products # names_count = {} # for name in products["name"]: # if name in names_count: # names_count[name] += 1 # else: # names_count = 1 # pairs = [] # for name, count in names_count.items(): # for i in range(count): # pairs.append([name, count]) # data_p_vs_c = pandas.DataFrame(pairs, columns=["Products", "Quantity"]) home_md = Markdown(""" <|toggle|theme|> <|container| # <center>**Rapid~Receipt**{: .color-primary} |Welcome Admin</center> <|layout|columns=2 1|gap=30px|hover_text=true| <| ### List of products <|Table|expandable| <|{products}|table|width=100%|> |> |> <| ### Available of Products <|{data}|chart|type=pie|values=Area|labels=Country|> |> |> ### Products sell |> """)
|
from taipy.gui import Markdown, notify, navigate from database import insert_one_collection, all_prodcuts image1 = "https://www.identixweb.com/wp-content/uploads/2022/01/Add-Customization-for-Custom-Products.png" image2 = "https://img.freepik.com/free-vector/online-wishes-list-concept-illustration_114360-3900.jpg" name = "" price = "" expiry = "" pid = "" def submit_action(state): if state.pid == "" or state.price == "" or state.expiry == "" or state.pid == "": notify(state, 'error', "Product data is invalid") return product = { "pid": int(state.pid), "name": state.name, "price": state.price, "expiry": state.expiry, "isavailable": True, } insert_one_collection(product) notify(state, 'info', "Product inserted") navigate(state, to="/home") addproduct_md = Markdown(""" <|toggle|theme|> <|container| ## Add **Product**{: .color-primary} π¦ <| <|50 50|layout|class_name= card| <| <|layout|columns= 1 1| <| #### Product Id: <|{pid}|input|> |> <| #### Product Name: <|{name}|input|> |> |> <br/><br/> <br/> <| <|layout|columns = 1 1 | <| #### Product Price: <|{price}|label=Price|input|> |> <| #### Product Expiry: <|{expiry}|input|> |> |> <br/> <|submit|button|on_action=submit_action|> |> |> <|{image2}|image|height=500px|width=500px|> |> |> |> """)
|
from taipy.gui import Markdown img1 = "https://www.identixweb.com/wp-content/uploads/2022/01/Add-Customization-for-Custom-Products.png" developer_md = Markdown(""" <|toggle|theme|> ## Our Team **Mahi**{: .color-primary} <|container <|layout|columns= 1 1 1 |gap=30px| <| <|{img1}|image|width=100%|> Suruchi |> <| <|{img1}|image|width=100%|> Shoaib |> <|{img1}|image|width=100%|> Shivam |> |> """)
|
from pages.dialogs.dialog_roc_md import * from pages.compare_models_md import * from pages.data_visualization_md import * from pages.databases_md import * from pages.model_manager_md import * dialog_md = """ <|dialog|open={dr_show_roc}|title=ROC Curve|partial={dialog_partial_roc}|on_action=delete_dialog_roc|labels=Close|width=1000px|> """
|
# νΌλ νλ ¬ λν μμ db_confusion_matrix_md = """ <|part|render={db_table_selected=='Confusion Matrix'}| <center> <|{score_table}|table|height=200px|width=400px|show_all=True|> </center> |> """ # νμ΅ λ°μ΄ν° μΈνΈμ λν ν
μ΄λΈ db_train_dataset_md = """ <|part|render={db_table_selected=='Training Dataset'}| <|{train_dataset}|table|width=1400px|height=560px|> |> """ # μμΈ‘ λ°μ΄ν° μΈνΈμ λν ν
μ΄λΈ db_forecast_dataset_md = """ <|part|render={db_table_selected=='Forecast Dataset'}| <center> <|{values}|table|height=560px|width=800px|style={get_style}|> </center> |> """ # ν
μ€νΈ λ°μ΄ν° μΈνΈμ λν ν
μ΄λΈ db_test_dataset_md = """ <|part|render={db_table_selected=='Test Dataset'}| <|{test_dataset}|table|width=1400px|height=560px|> |> """ # νμν ν
μ΄λΈμ μ ννλ μ νκΈ° db_table_selector = ['Training Dataset', 'Test Dataset', 'Forecast Dataset', 'Confusion Matrix'] db_table_selected = db_table_selector[0] # μ 체 νμ΄μ§λ₯Ό λ§λ€κΈ° μν λ¬Έμμ΄ μ§κ³ db_databases_md = """ # λ°μ΄ν°λ² μ΄μ€ <|layout|columns=2 2 1|columns[mobile]=1| <| **Algorithm**: \n \n <|{mm_algorithm_selected}|selector|lov={mm_algorithm_selector}|dropdown=True|> |> <| **Table**: \n \n <|{db_table_selected}|selector|lov={db_table_selector}|dropdown=True|> |> <br/> <br/> <|{PATH_TO_TABLE}|file_download|name=table.csv|label=Download table|> |> """ + db_test_dataset_md + db_confusion_matrix_md + db_train_dataset_md + db_forecast_dataset_md
|
from sklearn.metrics import f1_score import pandas as pd import numpy as np cm_height_histo = "100%" cm_dict_barmode = {"barmode": "stack","margin":{"t":30}} cm_options_md = "height={cm_height_histo}|width={cm_height_histo}|layout={cm_dict_barmode}" cm_compare_models_md = """ # λͺ¨λΈ λΉκ΅ <br/> <br/> <br/> <|layout|columns= 1 1 1|columns[mobile]=1| <|{accuracy_graph}|chart|type=bar|x=Pipeline|y[1]=Accuracy Model|y[2]=Accuracy Baseline|title=Accuracy|""" + cm_options_md + """|> <|{f1_score_graph}|chart|type=bar|x=Pipeline|y[1]=F1 Score Model|y[2]=F1 Score Baseline|title=F1 Score|""" + cm_options_md + """|> <|{score_auc_graph}|chart|type=bar|x=Pipeline|y[1]=AUC Score Model|y[2]=AUC Score Baseline|title=AUC Score|""" + cm_options_md + """|> |> """ def c_update_metrics(scenario, pipeline): """μ΄ ν¨μλ νμ΄νλΌμΈμ μ¬μ©νμ¬ μλ리μ€μ λ©νΈλ¦μ μ
λ°μ΄νΈν©λλ€. Args: scenario (scenario): μ νν μλλ¦¬μ€ pipeline (str): μ νν νμ΄νλΌμΈμ μ΄λ¦ Returns: obj: μ¬λ¬ κ°, λ©νΈλ¦μ λνλ΄λ λͺ©λ‘ """ metrics = scenario.pipelines[pipeline].metrics.read() number_of_predictions = metrics['number_of_predictions'] number_of_good_predictions = metrics['number_of_good_predictions'] number_of_false_predictions = metrics['number_of_false_predictions'] accuracy = np.around(metrics['accuracy'], decimals=2) f1_score = np.around(metrics['f1_score'], decimals=2) score_auc = np.around(scenario.pipelines[pipeline].score_auc.read(),decimals=2) dict_ftpn = metrics['dict_ftpn'] fp_ = dict_ftpn['fp'] tp_ = dict_ftpn['tp'] fn_ = dict_ftpn['fn'] tn_ = dict_ftpn['tn'] return number_of_predictions, accuracy, f1_score, score_auc, number_of_good_predictions, number_of_false_predictions, fp_, tp_, fn_, tn_ def compare_charts(accuracies, f1_scores, scores_auc, names): """μ΄ ν¨μλ λͺ¨λΈ λΉκ΅ νμ΄μ§μμ μ¬μ©λλ pandas λ°μ΄ν° νλ μ(μ°¨νΈ)μ μμ±ν©λλ€. Args: accuracies (list): μ νλ λͺ©λ‘ f1_scores (list): f1 μ μ λͺ©λ‘ scores_auc (list): auc μ μ λͺ©λ‘ names (list): μλλ¦¬μ€ μ΄λ¦ λͺ©λ‘ Returns: pd.DataFrame: μΈ κ°μ λ°μ΄ν°νλ μμ κ²°κ³Ό """ accuracy_graph = pd.DataFrame(create_metric_dict(accuracies, "Accuracy", names)) f1_score_graph = pd.DataFrame(create_metric_dict(f1_scores, "F1 Score", names)) score_auc_graph = pd.DataFrame(create_metric_dict(scores_auc, "AUC Score", names)) return accuracy_graph, f1_score_graph, score_auc_graph def compare_models_baseline(scenario,pipelines): """μ΄ ν¨μλ νμ΄νλΌμΈ λΉκ΅λ₯Ό μν κ°μ²΄λ₯Ό μμ±ν©λλ€. Args: scenario (scenario): μ νν μλλ¦¬μ€ pipelines (str): μ νν νμ΄νλΌμΈμ μ΄λ¦ Returns: pd.DataFrame: μΈ κ°μ λ°μ΄ν°νλ μμ κ²°κ³Ό """ accuracies = [] f1_scores = [] scores_auc = [] names = [] for pipeline in pipelines: (_,accuracy,f1_score,score_auc,_,_,_,_,_,_) = c_update_metrics(scenario, pipeline) accuracies.append(accuracy) f1_scores.append(f1_score) scores_auc.append(score_auc) names.append(pipeline[9:]) accuracy_graph,f1_score_graph, score_auc_graph = compare_charts(accuracies, f1_scores, scores_auc, names) return accuracy_graph, f1_score_graph, score_auc_graph def create_metric_dict(metric, metric_name, names): """μ΄ ν¨μλ Guiμ νμλ λ°μ΄ν° νλ μμμ μ¬μ©λ μ¬λ¬ νμ΄νλΌμΈμ λν λ©νΈλ¦ μ¬μ μ μμ±ν©λλ€. Args: metric (list): λ©νΈλ¦ κ° metric_name (str): λ©νΈλ¦μ μ΄λ¦ names (list): μλλ¦¬μ€ μ΄λ¦ λͺ©λ‘ Returns: dict: pandas λ°μ΄ν°νλμμ μ¬μ©λλ μ¬μ """ metric_dict = {} initial_list = [0]*len(names) metric_dict["Pipeline"] = names for i in range(len(names)): current_list = initial_list.copy() current_list[i] = metric[i] metric_dict[metric_name +" "+ names[i].capitalize()] = current_list return metric_dict
|
# Roc λ€μ΄μΌλ‘κ·Έ dr_show_roc = False def show_roc_fct(state): state.dr_show_roc = True def delete_dialog_roc(state): state.dr_show_roc = False dialog_roc = """ <center> <|{roc_dataset}|chart|x=False positive rate|y[1]=True positive rate|label[1]=True positive rate|height=500px|width=900px|type=scatter|> </center> """
|
from taipy.gui import Gui from page.page import * if __name__ == "__main__": Gui(page).run( use_reloader=True, title="Wine π· production by Region and Year", dark_mode=False, )
|
from taipy.core.config import Config from config.config import df_wine_production page = """ # Wine production by Region and Year ## Data for all the regions: <|{df_wine_production}|table|height=400px|width=95%|> """
|
import pandas as pd def add_wine_colors(df_wine): """Adds 2 columns with Args: df_wine (DataFrame): Data from the csv file (input for the whole app) Returns: df_wine_with_colors: DataFrame with all the input columns plus 2 nexw ones, 'red_and_rose' and 'white', and drops 2 columns that are not needed """ print("add wine color columns") df_wine_with_colors = df_wine.reset_index(drop=True) df_wine_with_colors["red_and_rose"] = 0 df_wine_with_colors["white"] = 0 # General case: df_wine_with_colors.loc[ df_wine_with_colors["wine_type"].str.contains("ROUGE"), "red_and_rose" ] = 1 df_wine_with_colors.loc[ df_wine_with_colors["wine_type"].str.contains("BLANC"), "white" ] = 1 # For some reason, there is some lines where the information about wine color is in the name: df_wine_with_colors.loc[ df_wine_with_colors["AOC"].str.contains("Rouge") & df_wine_with_colors["wine_type"].str.contains("NORD - EST"), "red_and_rose", ] = 1 df_wine_with_colors.loc[ df_wine_with_colors["AOC"].str.contains("Blanc") & df_wine_with_colors["wine_type"].str.contains("NORD - EST"), "white", ] = 1 # Droip unnecessary columns df_wine_with_colors = df_wine_with_colors.drop(columns=["data_type", "wine_type"]) return df_wine_with_colors
|
import taipy as tp from taipy.core.config import Config # Loading of the TOML Config.load("config/taipy-config.toml") # Get the scenario configuration scenario_cfg = Config.scenarios["SCENARIO_WINE"] tp.Core().run() scenario_wine = tp.create_scenario(scenario_cfg) scenario_wine.submit() df_wine_production = scenario_wine.WINE_PRODUCTION_WITH_COLORS.read()
|
from taipy.gui import Gui from tensorflow.keras import models from PIL import Image # to change img path to actual image import numpy as np class_names = { 0:'airplane', 1:'automobile', 2:'bird', 3:'cat', 4:'deer', 5:'dog', 6:'frog', 7:'horse', 8:'ship', 9:'truck', } model = models.load_model("baseline_mariya.keras") def image_predict(model, path_to_img): img = Image.open(path_to_img) img = img.convert("RGB") img = img.resize((32,32)) data = np.asarray(img) data = data/255 probs = model.predict(np.array([data])[:1]) top_prob = probs.max() top_pred = class_names[np.argmax(probs)] return top_prob,top_pred # index = "<h1>Kaise Ho!!</h1>" # index = "# Kaise Ho!!" img_path = "img.png" content = "" prob = 0 pred = "" index = """ <|text-center| <|{"logo.png"}|image|width=12vw|> <|{content}|file_selector|extensions=.png,.jpeg|> Select an image from your file system <|{pred}|> <|{img_path}|image|> <|{prob}|indicator|value={prob}|min=0|max=100|width=25vw|> > """ def on_change(state, var_name,var_value): if var_name == "content": top_prob,top_pred = image_predict(model,var_value) state.prob = round(top_prob*100) state.pred = "This is a " + top_pred state.img_path = var_value # print(var_name, var_value) app = Gui(page=index) if __name__ == "__main__": app.run(use_reloader=True) # means we dont need to type python classifier.py to run it again just refresh the page
|
from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.document_loaders import TextLoader loader = TextLoader("data/data_2.0.txt") # Use this line if you only need data.txt text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=0) data = loader.load() texts = text_splitter.split_documents(data) from langchain.vectorstores import Chroma, Pinecone from langchain.embeddings.openai import OpenAIEmbeddings from dotenv import load_dotenv import os import time load_dotenv() OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY) print(len(texts)) for i in range(0, len(texts), 100): try: db2 = Chroma.from_documents( texts[i : i + min(100, len(texts) - i)], embeddings, persist_directory="chroma_db", ) except ValueError: pass time.sleep(10) from langchain.chains import RetrievalQAWithSourcesChain from langchain import OpenAI from langchain.vectorstores import Chroma from langchain.embeddings.openai import OpenAIEmbeddings import os embeddings = OpenAIEmbeddings() docsearch = Chroma(persist_directory="chroma_db", embedding_function=embeddings) chain = RetrievalQAWithSourcesChain.from_chain_type( OpenAI(temperature=0), chain_type="stuff", retriever=docsearch.as_retriever(), reduce_k_below_max_tokens=True, ) user_input = input("What's your question: ") result = chain({"question": user_input}, return_only_outputs=True) print("Answer: " + result["answer"].replace("\n", " ")) print("Source: " + result["sources"])
|
from langchain.embeddings.openai import OpenAIEmbeddings from dotenv import load_dotenv import os load_dotenv() OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") from langchain.chains import RetrievalQAWithSourcesChain from langchain import OpenAI from langchain.vectorstores import Chroma from langchain.embeddings.openai import OpenAIEmbeddings from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import CharacterTextSplitter from langchain.llms import OpenAI from langchain.chains import ConversationalRetrievalChain from langchain.memory import ConversationBufferMemory memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) import os embeddings = OpenAIEmbeddings() docsearch = Chroma(persist_directory="chroma_db", embedding_function=embeddings) chain = RetrievalQAWithSourcesChain.from_chain_type( OpenAI(temperature=0), chain_type="stuff", retriever=docsearch.as_retriever(), reduce_k_below_max_tokens=True, ) qa = ConversationalRetrievalChain.from_llm( OpenAI(temperature=0), docsearch.as_retriever(), memory=memory, ) while True: user_input = input("What's your question: ") if len(user_input) == 0: break print( docsearch.similarity_search_with_score( query=user_input, distance_metric="cos", k=6 ) ) result = qa({"question": user_input}) print("Answer: " + result["answer"])
|
import os import sys import openai from langchain.chains import RetrievalQA from langchain.chat_models import ChatOpenAI from langchain.document_loaders import DirectoryLoader, TextLoader from langchain.embeddings import OpenAIEmbeddings from langchain.indexes import VectorstoreIndexCreator from langchain.indexes.vectorstore import VectorStoreIndexWrapper from langchain.llms import OpenAI from langchain.vectorstores import Chroma import constants os.environ["OPENAI_API_KEY"] = constants.APIKEY # Enable to save to disk & reuse the model (for repeated queries on the same data) PERSIST = False query = input("What's your question?") if PERSIST and os.path.exists("persist"): print("Reusing index...\n") vectorstore = Chroma( persist_directory="persist", embedding_function=OpenAIEmbeddings() ) index = VectorStoreIndexWrapper(vectorstore=vectorstore) else: # loader = TextLoader("data/data.txt") # Use this line if you only need data.txt loader = DirectoryLoader("data/") if PERSIST: index = VectorstoreIndexCreator( vectorstore_kwargs={"persist_directory": "persist"} ).from_loaders([loader]) else: index = VectorstoreIndexCreator().from_loaders([loader]) chain = RetrievalQA.from_chain_type( llm=ChatOpenAI(model="gpt-3.5-turbo"), retriever=index.vectorstore.as_retriever(search_kwargs={"k": 1}), ) print(chain.run(query))
|
s = open("data/data.txt", "r") s = s.read().replace("\n", "") with open("data/new_data.txt", "w") as x: x.write(s)
|
import requests from bs4 import BeautifulSoup from urllib.parse import urlparse, urljoin def scrape_domain_and_subdomains(base_url, file_path): visited_urls = set() def scrape(url): response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.content, "html.parser") div_elements = soup.select("div.md-content") text = "" for div in div_elements: text += div.get_text() append_to_text_file(text, file_path) links = soup.find_all("a") for link in links: href = link.get("href") if href: subdomain_url = urljoin(url, href) parsed_url = urlparse(subdomain_url) if ( parsed_url.netloc.endswith("docs.taipy.io") and subdomain_url not in visited_urls ): visited_urls.add(subdomain_url) scrape(subdomain_url) scrape(f"http://{base_url}") print(visited_urls) def append_to_text_file(content, file_path): with open(file_path, "a", encoding="utf-8") as file: file.write(content) file.write("\n") # Example usage: base_url = "docs.taipy.io/en/latest/" # Replace with the base domain to scrape (without the protocol) file_path = "data/data_2.0.txt" # Replace with the desired file path scrape_domain_and_subdomains(base_url, file_path)
|
# This is a sample Python script. # Press Maj+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. # Press the green button in the gutter to run the script. if __name__ == '__main__': print_hi('PyCharm') # See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
import taipy as tp from taipy.gui import Gui, notify from taipy.config import Config import numpy as np import pandas as pd BUSINESS_PATH = "data/yelp_business.csv" # Load the business data using pandas business_df = pd.read_csv(BUSINESS_PATH) # Remove quotation marks from the name business_df.name = business_df.name.str[1:-1] # Taipy Core Config.load("config/config.toml") Config.configure_data_node(id="review_data", read_fct_params=("data/yelp_review.csv",)) scenario_object = Config.scenarios["scenario"] business_name = business_df.name[0] reviews = None def on_selection(state): """ Re-runs the scenario when the user selects a business. Args: - state: state of the app """ notify(state, "info", "Running query...") business_scenarios = [ s for s in tp.get_scenarios() if s.name == state.business_name ] if len(business_scenarios) > 0: scenario = business_scenarios[0] else: scenario = tp.create_scenario(scenario_object, name=state.business_name) scenario.business_name.write(state.business_name) tp.submit(scenario) state.reviews = scenario.parsed_reviews.read() notify(state, "success", "Query finished") page = """ # Querying **Big Data**{: .color-primary} with Taipy and Dask ## Select a **business**{: .color-primary} <|{business_name}|selector|lov={list(business_df.name)}|dropdown|on_change=on_selection|> ## Average **stars**{: .color-primary} for that business: <|{"β"*int(np.mean(reviews.stars))}|text|raw|> <|{round(np.mean(reviews.stars),2)}|indicator|value={np.mean(reviews.stars)}|min=1|max=5|width=30%|> ## **Reviews**{: .color-primary} for that business: <|{reviews}|table|width=100%|> """ def on_init(state): scenario = tp.create_scenario(scenario_object, name=state.business_name) tp.submit(scenario) state.reviews = scenario.parsed_reviews.read() if __name__ == "__main__": tp.Core().run() Gui(page).run()
|
import dask.dataframe as dd def get_data(path_to_csv: str, optional: str = None): """ Loads a csv file into a dask dataframe. Converts the date column to datetime. Args: - path_to_csv: path to the csv file - optional: optional argument (currently necessary to fix Core bug with generic data nodes) Returns: - dataset: dask dataframe """ dataset = dd.read_csv(path_to_csv) dataset["date"] = dd.to_datetime(dataset["date"]) return dataset def write_function(): """ Useless function to fix Core bug with generic data nodes. """ return None
|
import pandas as pd import dask.dataframe as dd def get_id_from_name(name: str, business_dict: dict): """ Returns the business_id from the name of the business. Args: - name: name of the business - business_dict: dict with the name as key and the business_id as value Returns: - business_id: id of the business """ business_id = business_dict[name] return business_id def parse_business_data(data: dd.DataFrame): """ Parses the reviews of a business. Args: - data: dask dataframe with the reviews of a business Returns: - data: dask dataframe with the parsed reviews """ # Sort data by useful data = data.sort_values(by="useful", ascending=False) # Keep only the stars, date and text columns data = data[["stars", "date", "text"]] return data def get_business_data(business_id: str, data: dd.DataFrame): """ Returns a dask dataframe with the reviews of a business. Args: - business_id: id of the business - data: dask dataframe with the reviews Returns: - df_business: dask dataframe with the reviews of the business """ df_business = data[(data.business_id == business_id)].compute() return df_business def create_business_dict(business_df: pd.DataFrame): """ Creates a dict with the name as key and the business_id as value. Args: - business_df: pandas dataframe with the business data Returns: - business_dict: dict with the name as key and the business_id as value """ # Remove quotation marks from the name business_df.name = business_df.name.str[1:-1] business_dict = dict(zip(business_df.name, business_df.business_id)) print(business_dict) return business_dict
|
import time import pandas as pd import dask.dataframe as dd def task1(path_to_original_data: str): print("__________________________________________________________") print("1. TASK 1: DATA PREPROCESSING AND CUSTOMER SCORING ...") start_time = time.perf_counter() # Start the timer # Step 1: Read data using Dask df = dd.read_csv(path_to_original_data) # Step 2: Simplify the customer scoring formula df['CUSTOMER_SCORE'] = ( 0.5 * df['TotalPurchaseAmount'] / 1000 + 0.3 * df['NumberOfPurchases'] / 10 + 0.2 * df['AverageReviewScore'] ) # Save all customers to a new CSV file scored_df = df[["CUSTOMER_SCORE", "TotalPurchaseAmount", "NumberOfPurchases", "TotalPurchaseTime"]] pd_df = scored_df.compute() end_time = time.perf_counter() # Stop the timer execution_time = (end_time - start_time) * 1000 # Calculate the time in milliseconds print(f"Time of Execution: {execution_time:.4f} ms") return pd_df def task2(scored_df, payment_threshold, score_threshold): print("__________________________________________________________") print("2. TASK 2: FEATURE ENGINEERING AND SEGMENTATION ...") payment_threshold, score_threshold = float(payment_threshold), float(score_threshold) start_time = time.perf_counter() # Start the timer df = scored_df # Feature: Indicator if customer's total purchase is above the payment threshold df['HighSpender'] = (df['TotalPurchaseAmount'] > payment_threshold).astype(int) # Feature: Average time between purchases df['AverageTimeBetweenPurchases'] = df['TotalPurchaseTime'] / df['NumberOfPurchases'] # Additional computationally intensive features df['Interaction1'] = df['TotalPurchaseAmount'] * df['NumberOfPurchases'] df['Interaction2'] = df['TotalPurchaseTime'] * df['CUSTOMER_SCORE'] df['PolynomialFeature'] = df['TotalPurchaseAmount'] ** 2 # Segment customers based on the score_threshold df['ValueSegment'] = ['High Value' if score > score_threshold else 'Low Value' for score in df['CUSTOMER_SCORE']] end_time = time.perf_counter() # Stop the timer execution_time = (end_time - start_time) * 1000 # Calculate the time in milliseconds print(f"Time of Execution: {execution_time:.4f} ms") return df def task3(df: pd.DataFrame, metric): print("__________________________________________________________") print("3. TASK 3: SEGMENT ANALYSIS ...") start_time = time.perf_counter() # Start the timer # Detailed analysis for each segment: mean/median of various metrics segment_analysis = df.groupby('ValueSegment').agg({ 'CUSTOMER_SCORE': metric, 'TotalPurchaseAmount': metric, 'NumberOfPurchases': metric, 'TotalPurchaseTime': metric, 'HighSpender': 'sum', # Total number of high spenders in each segment 'AverageTimeBetweenPurchases': metric }).reset_index() end_time = time.perf_counter() # Stop the timer execution_time = (end_time - start_time) * 1000 # Calculate the time in milliseconds print(f"Time of Execution: {execution_time:.4f} ms") return segment_analysis def task4(df: pd.DataFrame, segment_analysis: pd.DataFrame, summary_statistic_type: str): print("__________________________________________________________") print("4. TASK 4: ADDITIONAL ANALYSIS BASED ON SEGMENT ANALYSIS ...") start_time = time.perf_counter() # Start the timer # Filter out the High Value customers high_value_customers = df[df['ValueSegment'] == 'High Value'] # Use summary_statistic_type to calculate different types of summary statistics if summary_statistic_type == 'mean': average_purchase_high_value = high_value_customers['TotalPurchaseAmount'].mean() elif summary_statistic_type == 'median': average_purchase_high_value = high_value_customers['TotalPurchaseAmount'].median() elif summary_statistic_type == 'max': average_purchase_high_value = high_value_customers['TotalPurchaseAmount'].max() elif summary_statistic_type == 'min': average_purchase_high_value = high_value_customers['TotalPurchaseAmount'].min() median_score_high_value = high_value_customers['CUSTOMER_SCORE'].median() # Fetch the summary statistic for 'TotalPurchaseAmount' for High Value customers from segment_analysis segment_statistic_high_value = segment_analysis.loc[segment_analysis['ValueSegment'] == 'High Value', 'TotalPurchaseAmount'].values[0] # Create a DataFrame to hold the results result_df = pd.DataFrame({ 'SummaryStatisticType': [summary_statistic_type], 'AveragePurchaseHighValue': [average_purchase_high_value], 'MedianScoreHighValue': [median_score_high_value], 'SegmentAnalysisHighValue': [segment_statistic_high_value] }) end_time = time.perf_counter() # Stop the timer execution_time = (end_time - start_time) * 1000 # Calculate the time in milliseconds print(f"Time of Execution: {execution_time:.4f} ms") return result_df if __name__ == "__main__": t1 = task1("data/SMALL_amazon_customers_data.csv") t2 = task2(t1, 1500, 1.5) t3 = task3(t2, "mean") t4 = task4(t2, t3, "mean") print(t4)
|
from recsys.recsys import page_scenario_manager from taipy.gui import Gui gui = Gui(page_scenario_manager) gui.run()
|
import pandas as pd import numpy as np TEST_RATIO = 0.2 MOVIELENS_DATA_PATH = "u.data" MOVIE_DATA_PATH = "u.item" def convert_data_to_dataframe(data_path: str, movie_path: str): data = pd.read_table(data_path) data.columns = ["u_id", "i_id", "rating", "timestamp"] data_sort = data.sort_values(by=["u_id"]) movie_name = pd.read_table( movie_path, sep='|', encoding="latin-1", header=None) movie_name.drop([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], inplace=True, axis=1) movie_name.rename(columns={0: "movieId", 1: "title"}, inplace=True) return data_sort, movie_name movies_list = [] print("\nReading the ratings file...") ratings, movie_name = convert_data_to_dataframe( MOVIELENS_DATA_PATH, MOVIE_DATA_PATH) userIds = ratings.u_id.unique() trainIds = [] testIds = [] print("Splitting the ratings data...") for u in userIds: rating_of_u = ratings.loc[ratings.u_id == u] trainIds_sample = rating_of_u.sample( frac=(1-TEST_RATIO), random_state=7) testIds_sample = rating_of_u.drop(trainIds_sample.index.tolist()) for _, rating in trainIds_sample.iterrows(): if rating.i_id not in movies_list: # Append new movie's Id to the movie list movies_list.append(rating.u_id) trainIds_sample = trainIds_sample.index.values trainIds_sample.sort() trainIds = np.append(trainIds, trainIds_sample) testIds_sample = testIds_sample.index.values testIds_sample.sort() testIds = np.append(testIds, testIds_sample) print("Done.") print("Write ratings to new file...") train = ratings.loc[ratings.index.isin(trainIds)] train.to_csv("rating_train.csv", index=False) test = ratings.loc[ratings.index.isin(testIds)] test.to_csv("rating_test.csv", index=False) movie_name.to_csv("movie.csv", index=False) print("Done.")
|
import pandas as pd from datetime import datetime data = pd.read_csv("dataset/rating_train.csv") timestamp = data.timestamp.to_list() date = [] for time in timestamp: date.append(datetime.fromtimestamp(time)) data["timestamp"] = date data.to_csv("data.csv", index=False)
|
import pandas as pd import numpy as np from scipy import sparse class DataLoader: def __init__(self): self.__train_data = None self.__val_data = None self.__test_data = None def __create_id_mapping(self): if self.__val_data: unique_uIds = pd.concat( [self.__train_data.u_id, self.__test_data.u_id, self.__val_data.u_id] ).unique() unique_iIds = pd.concat( [self.__train_data.i_id, self.__test_data.i_id, self.__val_data.i_id] ).unique() else: unique_uIds = pd.concat( [self.__train_data.u_id, self.__test_data.u_id] ).unique() unique_iIds = pd.concat( [self.__train_data.i_id, self.__test_data.i_id] ).unique() self.user_dict = {uId: idx for idx, uId in enumerate(unique_uIds)} self.item_dict = {iId: idx for idx, iId in enumerate(unique_iIds)} def __preprocess(self, data): """Map the id of all users and items according to user_dict and item_dict. To create the user_dict, all user ID in the training set is first sorted, then the first ID is map to 0 and so on. Do the same for item_dict. This process is done via `self.__create_id_mapping()`. Args: data (Dataframe): The dataset that need to be preprocessed. Returns: ndarray: The array with all id mapped. """ # data['u_id'] = data['u_id'].replace(self.user_dict) # data['i_id'] = data['i_id'].replace(self.item_dict) data["u_id"] = data["u_id"].map(self.user_dict) data["i_id"] = data["i_id"].map(self.item_dict) # Tag unknown users/items with -1 (when val) data.fillna(-1, inplace=True) data["u_id"] = data["u_id"].astype(np.int32) data["i_id"] = data["i_id"].astype(np.int32) return data[["u_id", "i_id", "rating"]].values def load_csv2ndarray( self, train_data, test_data, val_path="rating_val.csv", use_val=False, columns=["u_id", "i_id", "rating", "timestamp"], ): """ Load training set, validate set and test set via `.csv` file. Each as `ndarray`. Args: train_path (string): path to the training set csv file inside self.__data_folder test_path (string): path to the testing set csv file inside self.__data_folder val_path (string): path to the validating set csv file inside self.__data_folder use_val (boolean): Denote if loading validate data or not. Defaults to False. columns (list): Columns name for DataFrame. Defaults to ['u_id', 'i_id', 'rating', 'timestamp']. Returns: train, val, test (np.array): Preprocessed data. """ self.__train_data = train_data self.__test_data = test_data if use_val: self.__val_data = self.__read_csv(val_path, columns) self.__create_id_mapping() self.__train_data = self.__preprocess(self.__train_data) self.__test_data = self.__preprocess(self.__test_data) if use_val: self.__val_data = self.__preprocess(self.__val_data) return self.__train_data, self.__val_data, self.__test_data else: return self.__train_data, self.__test_data def load_genome_fromcsv( self, genome_file="genome_scores.csv", columns=["i_id", "g_id", "score"], reset_index=False, ): """ Load genome scores from file. Args: genome_file (string): File name that contain genome scores. Must be in csv format. columns (list, optional): Columns name for DataFrame. Must be ["i_id", "g_id", "score"] or ["i_id", "score", "g_id"]. reset_index (boolean): Reset the genome_tag column or not. Defaults to False. Returns: scores (DataFrame) """ genome = pd.read_csv( self.__genome_folder + "/" + genome_file, header=0, names=columns ) if reset_index: tag_map = { genome.g_id: newIdx for newIdx, genome in genome.loc[genome.i_id == 1].iterrows() } genome["g_id"] = genome["g_id"].map(tag_map) genome["i_id"] = genome["i_id"].map(self.item_dict) genome.fillna(0, inplace=True) return sparse.csr_matrix( (genome["score"], (genome["i_id"].astype(int), genome["g_id"].astype(int))) ).toarray()
|
from taipy import Config, Scope from functions.funtions import preprocess_data, fit, predict from config.svd_config import ( n_epochs_cfg, n_factors_cfg, learning_rate_cfg, qi_cfg, bi_cfg, bu_cfg, pu_cfg, ) from config.kNN_config import ( x_id_cfg, n_k_neighboor_cfg, n_min_k_cfg, sim_measure_cfg, list_ur_ir_cfg, similarity_matrix_cfg, users_id_cfg, items_id_cfg, ) TRAIN_DATA_PATH = "dataset/rating_train.csv" TEST_DATA_PATH = "dataset/rating_test.csv" MOVIE_DATA_PATH = "dataset/movie.csv" train_dataset_cfg = Config.configure_data_node( id="train_dataset", storage_type="csv", path=TRAIN_DATA_PATH, scope=Scope.GLOBAL, cacheable=True, ) test_dataset_cfg = Config.configure_data_node( id="test_dataset", storage_type="csv", path=TEST_DATA_PATH, scope=Scope.GLOBAL, cacheable=True, ) movie_name_cfg = Config.configure_data_node( id="movie_name", storage_type="csv", path=MOVIE_DATA_PATH, scope=Scope.GLOBAL, cacheable=True, ) trainset_cfg = Config.configure_data_node( id="trainset", scope=Scope.PIPELINE, cacheable=True) testset_cfg = Config.configure_data_node( id="testset", scope=Scope.PIPELINE, cacheable=True) true_testset_movies_id_cfg = Config.configure_data_node( id="true_testset_movies_id", scope=Scope.PIPELINE, cacheable=True ) algorithm_cfg = Config.configure_in_memory_data_node( id="algorithm", default_data="kNN") global_mean_cfg = Config.configure_data_node( id="global_mean", cope=Scope.GLOBAL, cacheable=True ) predictions_cfg = Config.configure_data_node( id="predictions", scope=Scope.PIPELINE) # Config task load_data_task_cfg = Config.configure_task( id="load_data", function=preprocess_data, input=[train_dataset_cfg, test_dataset_cfg, movie_name_cfg], output=[trainset_cfg, testset_cfg, true_testset_movies_id_cfg], ) train_data_task_cfg = Config.configure_task( id="train_data", function=fit, input=[ trainset_cfg, sim_measure_cfg, n_factors_cfg, n_epochs_cfg, learning_rate_cfg, algorithm_cfg, ], output=[ similarity_matrix_cfg, list_ur_ir_cfg, users_id_cfg, items_id_cfg, global_mean_cfg, pu_cfg, qi_cfg, bu_cfg, bi_cfg, ], ) predict_task_cfg = Config.configure_task( id="predict_task", function=predict, input=[ testset_cfg, x_id_cfg, list_ur_ir_cfg, similarity_matrix_cfg, n_k_neighboor_cfg, n_min_k_cfg, users_id_cfg, items_id_cfg, global_mean_cfg, true_testset_movies_id_cfg, bu_cfg, bi_cfg, pu_cfg, qi_cfg, algorithm_cfg, ], output=predictions_cfg, ) # Config pipeline pipeline_cfg = Config.configure_pipeline( id="pipeline", task_configs=[load_data_task_cfg, train_data_task_cfg, predict_task_cfg], )
|
from taipy import Config, Scope x_id_cfg = Config.configure_data_node(id="x_id", default_data=1) n_min_k_cfg = Config.configure_data_node(id="n_min_k", default_data=10) n_k_neighboor_cfg = Config.configure_data_node( id="n_k_neighboor", default_data=1) sim_measure_cfg = Config.configure_in_memory_data_node( id="sim_measure", default_data="pcc") list_ur_ir_cfg = Config.configure_data_node( id="list_ur_ir", cope=Scope.GLOBAL, cacheable=True) similarity_matrix_cfg = Config.configure_data_node( id="similarity_matrix", cope=Scope.GLOBAL, cacheable=True) items_id_cfg = Config.configure_data_node( id="x_list", cope=Scope.GLOBAL, cacheable=True) users_id_cfg = Config.configure_data_node( id="y_list", cope=Scope.GLOBAL, cacheable=True)
|
from taipy import Config, Scope n_factors_cfg = Config.configure_data_node(id="n_factors", default_data=30) n_epochs_cfg = Config.configure_data_node(id="n_epochs", default_data=50) learning_rate_cfg = Config.configure_data_node(id="learning_rate", default_data=0.001) qi_cfg = Config.configure_data_node(id="qi", cope=Scope.GLOBAL, cacheable=True) pu_cfg = Config.configure_data_node(id="pu", cope=Scope.GLOBAL, cacheable=True) bu_cfg = Config.configure_data_node(id="bu", cope=Scope.GLOBAL, cacheable=True) bi_cfg = Config.configure_data_node(id="bi", cope=Scope.GLOBAL, cacheable=True)
|
import taipy as tp from taipy.config import Config from taipy.gui import notify, Markdown import pandas as pd import numpy as np from helper.knn_helper import calculate_precision_recall from config.config import pipeline_cfg Config.configure_global_app(clean_entities_enabled=True) tp.clean_all_entities() scenario_cfg = Config.configure_scenario( id="scenario", pipeline_configs=pipeline_cfg) dataset = pd.read_csv("dataset/data.csv") dataset["timestamp"] = pd.to_datetime(dataset["timestamp"]) sim_measure_selector = ["pcc", "cosine"] selected_sim_measure = sim_measure_selector[0] model_selector = ["kNN", "MF"] selected_model = sim_measure_selector[0] # set up parameter of kNN model n_min_k, n_k_neighboor, x_id, top_k = 1, 10, 1, 1 # set up parameter of svd model n_epochs, n_factors, learning_rate = 30, 40, 0.001 results, y_id, y_id_real, results_real, recall, precision = ( None, None, None, None, None, None,) all_scenarios = tp.get_scenarios() [tp.delete(scenario.id) for scenario in all_scenarios if scenario.name is None] scenario_selector = [(scenario.id, scenario.name) for scenario in tp.get_scenarios()] def create_scenario(state): global selected_scenario print("Creating scenario...") scenario = tp.create_scenario(scenario_cfg) scenario.sim_measure.write(str(state.selected_sim_measure)) scenario.algorithm.write(str(state.selected_model)) scenario.n_min_k.write(int(state.n_min_k)) scenario.n_k_neighboor.write(int(state.n_k_neighboor)) scenario.x_id.write(int(state.x_id)) scenario.n_factors.write(int(state.n_factors)) scenario.n_epochs.write(int(state.n_epochs)) scenario.learning_rate.write(float(learning_rate)) selected_scenario = scenario.id update_scenario_selector(state, scenario) tp.submit(scenario) def submit_scenario(state): ( state.y_id, state.y_id_real, state.results_real, state.recall, state.precision, state.results, ) = ( None, None, [], None, None, [], ) print("Submitting scenario...") # Get the selected scenario: in this current step a single scenario is created then modified here. scenario = tp.get(selected_scenario) # Change the default parameters by writing in the datanodes if scenario.sim_measure.read() != state.selected_sim_measure: scenario.sim_measure.write(str(state.selected_sim_measure)) if scenario.n_min_k.read() != state.n_min_k: scenario.n_min_k.write(int(state.n_min_k)) if scenario.n_k_neighboor.read() != state.n_k_neighboor: scenario.n_k_neighboor.write(int(state.n_k_neighboor)) if scenario.x_id.read() != state.x_id: scenario.x_id.write(int(state.x_id)) if scenario.n_factors.read() != state.n_factors: scenario.n_factors.write(int(state.n_factors)) if scenario.n_epochs.read() != state.n_epochs: scenario.n_epochs.write(int(state.n_epochs)) if scenario.learning_rate.read() != state.learning_rate: scenario.learning_rate.write(float(learning_rate)) if scenario.algorithm.read() != state.selected_model: scenario.algorithm.write(str(state.selected_model)) # Execute the pipelines/code tp.submit(scenario) def update_scenario_selector(state, scenario): print("Updating scenario selector...") # Update the scenario selector state.scenario_selector += [(scenario.id, scenario.name)] def take_all_movies_rated_by_x_id(test_set, x_id): test_items = [] test_set = test_set.copy() for index in range(test_set.shape[0]): if test_set[index][0] == x_id: test_items.append(test_set[index]) test_items = np.array(test_items) return test_items def predicts(state): id, predict, id_real, predict_real, user_ratings = ( [], [], [], [], [],) scenario = tp.get(selected_scenario) movie_name = (scenario.movie_name.read()).title.to_numpy() print("'Predict' button clicked") result = scenario.predictions.read() result = result[result[:, 4].argsort()[::-1]] if state.top_k > result.shape[0]: notify( state, notification_type="error", message="Out of range, top_k max = {}".format(result.shape[0]), ) state.top_k = result.shape[0] top_k = state.top_k test_set = scenario.testset.read() true_testset_movies_id = scenario.true_testset_movies_id.read() test_set[:, 1] = true_testset_movies_id.T test_items = take_all_movies_rated_by_x_id(test_set, state.x_id) test_items = test_items[test_items[:, 2].argsort()[::-1]] for i in range(int(top_k)): id.append(int(result[i][3])) id_real.append(int(test_items[i][1])) for i, j in zip(id, id_real): predict.append(movie_name[(i - 1)]) predict_real.append(movie_name[(j - 1)]) state.y_id = np.array2string( np.array(id), precision=2, separator=", ", suppress_small=True) state.y_id_real = np.array2string( np.array(id_real), precision=2, separator=", ", suppress_small=True) state.results = predict state.results_real = predict_real for _, _, true_r, _, est in result: user_ratings.append([est, true_r]) user_ratings = np.array(user_ratings) state.precision, state.recall = calculate_precision_recall( user_ratings, top_k, 3) page_scenario_manager = Markdown("recsys/recsys.md")
|
import numpy as np from numba import njit def sgd( X, pu, qi, bu, bi, n_epochs, global_mean, n_factors, lr_pu, lr_qi, lr_bu, lr_bi, reg_pu, reg_qi, reg_bu, reg_bi, ): for epoch_ix in range(n_epochs): pu, qi, bu, bi, train_loss = _run_svd_epoch( X, pu, qi, bu, bi, global_mean, n_factors, lr_pu, lr_qi, lr_bu, lr_bi, reg_pu, reg_qi, reg_bu, reg_bi, ) return pu, qi, bu, bi, train_loss @njit def _run_svd_epoch( X, pu, qi, bu, bi, global_mean, n_factors, lr_pu, lr_qi, lr_bu, lr_bi, reg_pu, reg_qi, reg_bu, reg_bi, ): """Runs an SVD epoch, updating model weights (pu, qi, bu, bi). Args: X (ndarray): the training set. pu (ndarray): users latent factor matrix. qi (ndarray): items latent factor matrix. bu (ndarray): users biases vector. bi (ndarray): items biases vector. global_mean (float): ratings arithmetic mean. n_factors (int): number of latent factors. lr_pu (float, optional): Pu's specific learning rate. lr_qi (float, optional): Qi's specific learning rate. lr_bu (float, optional): bu's specific learning rate. lr_bi (float, optional): bi's specific learning rate. reg_pu (float, optional): Pu's specific regularization term. reg_qi (float, optional): Qi's specific regularization term. reg_bu (float, optional): bu's specific regularization term. reg_bi (float, optional): bi's specific regularization term. Returns: pu (ndarray): the updated users latent factor matrix. qi (ndarray): the updated items latent factor matrix. bu (ndarray): the updated users biases vector. bi (ndarray): the updated items biases vector. train_loss (float): training loss. """ residuals = [] for i in range(X.shape[0]): user, item, rating = int(X[i, 0]), int(X[i, 1]), X[i, 2] # Predict current rating pred = global_mean + bu[user] + bi[item] for factor in range(n_factors): pred += pu[user, factor] * qi[item, factor] err = rating - pred residuals.append(err) # Update biases bu[user] += lr_bu * (err - reg_bu * bu[user]) bi[item] += lr_bi * (err - reg_bi * bi[item]) # Update latent factors for factor in range(n_factors): puf = pu[user, factor] qif = qi[item, factor] pu[user, factor] += lr_pu * (err * qif - reg_pu * puf) qi[item, factor] += lr_qi * (err * puf - reg_qi * qif) residuals = np.array(residuals) train_loss = np.square(residuals).mean() return pu, qi, bu, bi, train_loss @njit def predict_svd_pair(u_id, i_id, global_mean, bu, bi, pu, qi): """Returns the model rating prediction for a given user/item pair. Args: u_id (int): a user id. i_id (int): an item id. Returns: pred (float): the estimated rating for the given user/item pair. """ user_known, item_known = False, False pred = global_mean if u_id != -1: user_known = True pred += bu[u_id] if i_id != -1: item_known = True pred += bi[i_id] if user_known and item_known: pred += np.dot(pu[u_id], qi[i_id]) return pred
|
import pandas as pd from prophet import Prophet from taipy import Config def clean_data(initial_dataset: pd.DataFrame): print("Cleaning Data") initial_dataset = initial_dataset.rename(columns={"Date": "ds", "Close": "y"}) initial_dataset['ds'] = pd.to_datetime(initial_dataset['ds']).dt.tz_localize(None) cleaned_dataset = initial_dataset.copy() return cleaned_dataset def retrained_model(cleaned_dataset: pd.DataFrame): print("Model Retraining") model = Prophet() model.fit(cleaned_dataset) return model def predict(model): periods = 365 return model.predict(model.make_future_dataframe(periods=periods)[-periods:])[['ds', 'yhat']].rename(columns = {'ds':'Date', 'yhat':'Close_Prediction'}) ## Input Data Nodes initial_dataset_cfg = Config.configure_data_node(id="initial_dataset", storage_type="csv", default_path='df.csv') cleaned_dataset_cfg = Config.configure_data_node(id="cleaned_dataset") clean_data_task_cfg = Config.configure_task(id="clean_data_task", function=clean_data, input=initial_dataset_cfg, output=cleaned_dataset_cfg, skippable=True) model_training_cfg = Config.configure_data_node(id="model_output") predictions_cfg = Config.configure_data_node(id="predictions") model_training_task_cfg = Config.configure_task(id="model_retraining_task", function=retrained_model, input=cleaned_dataset_cfg, output=model_training_cfg, skippable=True) predict_task_cfg = Config.configure_task(id="predict_task", function=predict, input=model_training_cfg, output=predictions_cfg, skippable=True) # Create our scenario configuration from our tasks scenario_cfg = Config.configure_scenario_from_tasks(id="stock", task_configs=[clean_data_task_cfg, model_training_task_cfg, predict_task_cfg]) """ import taipy as tp import yfinance as yf # Run of the Taipy Core service tp.Core().run() def get_stock_data(ticker, start): ticker_data = yf.download(ticker, start, dt.datetime.now()).reset_index() # downloading the stock data from START to TODAY ticker_data['Date'] = ticker_data['Date'].dt.tz_localize(None) return ticker_data tickers = {'MSFT':get_stock_data('MSFT', start_date), 'AAPL':get_stock_data('AAPL', start_date), 'GOOG':get_stock_data('GOOG', start_date)} def create_and_submit_scenario(stock_name): scenario_stock = tp.create_scenario(scenario_cfg, name=stock_name) scenario_stock.initial_dataset.path = f"{stock_name}.csv" scenario_stock.initial_dataset.write(tickers[stock_name]) tp.submit(scenario_stock) for stock_name in tickers.keys(): create_and_submit_scenario(stock_name) stocks = tp.get_scenarios() for stock in stocks: print(stock.name) print(stock.predictions.read()) """
|
from taipy.gui import Gui, notify import pandas as pd import yfinance as yf from taipy.config import Config import taipy as tp import datetime as dt Config.load('config_model_train.toml') scenario_cfg = Config.scenarios['stock'] def get_stock_data(ticker, start): ticker_data = yf.download(ticker, start, dt.datetime.now()).reset_index() # downloading the stock data from START to TODAY ticker_data['Date'] = ticker_data['Date'].dt.tz_localize(None) return ticker_data start_date = '2015-01-01' property_chart = {"type":"lines", "x":"Date", "y[1]":"Open", "y[2]":"Close", "y[3]":"High", "y[4]":"Low", "color[1]":"green", "color[2]":"grey", "color[3]":"red", "color[4]":"yellow" } df = pd.DataFrame([], columns = ['Date', 'High', 'Low', 'Open', 'Close']) df_pred = pd.DataFrame([], columns = ['Date','Close_Prediction']) stock_text = "No Stock to Show" chart_text = 'No Chart to Show' pred_text = 'No Prediction to Show' stock = "" stocks = [] page = """ <|toggle|theme|> # Stock Portfolio ### Choose the stock to show <|layout|columns=1 1| <|{f'The stock is {stock.name}' if stock else 'No Stock to Show'}|> <|{stock}|selector|lov={stocks}|dropdown|adapter={lambda s: s.name}|> <|Reset|button|on_action=reset|> <|Press for Stock|button|on_action=update_ticker_history|active={stock}|> <|Update Model|button|on_action=update_model|active={stock}|> <|{f'Monthly history of stock {stock.name}' if stock else 'No Chart to Show'}|> <|{df}|chart|properties={property_chart}|> |> <|{f'1 Year Close Prediction of Stock {stock.name}' if stock else 'No Prediction to Show'}|> <|{df_pred}|chart|x=Date|y=Close_Prediction|> """ def reset(state): state.stock = "" state.df = pd.DataFrame([], columns = ['Date', 'High', 'Low', 'Open', 'Close']) state.df_pred = pd.DataFrame([], columns = ['Date','Close_Prediction']) notify(state, 'success', 'Reset done!') def update_ticker_history(state): state.stock.initial_dataset.write(get_stock_data(state.stock.name, start_date)) on_change(state, "stock", state.stock) notify(state, 'success', 'History up-to-date! You should retrain the model') def on_change(state, var_name, var_value): if var_name == "stock" and var_value: state.df = state.stock.initial_dataset.read() state.df_pred = state.stock.predictions.read() def update_model(state): print("Update Model Clicked") tp.submit(state.stock) on_change(state, "stock", state.stock) notify(state, 'success', 'Model trained and charts up-to-date!') def on_init(state): tickers = {'MSFT':get_stock_data('MSFT', start_date), 'AAPL':get_stock_data('AAPL', start_date), 'GOOG':get_stock_data('GOOG', start_date)} def create_and_submit_scenario(stock_name): scenario_stock = tp.create_scenario(scenario_cfg, name=stock_name) scenario_stock.initial_dataset.path = f"{stock_name}.csv" scenario_stock.initial_dataset.write(tickers[stock_name]) tp.submit(scenario_stock) for stock_name in tickers.keys(): create_and_submit_scenario(stock_name) state.stocks = tp.get_scenarios() state.stock = state.stocks[0] tp.Core().run() Gui(page).run()
|
from taipy import Gui import pandas as pd # Interactive GUI and state, we maintain states for each individual client # hence we can have multiple clients with each client having its own state, # change of the state of one client will not affect the other client's state. # Each client has its own state and global values are made local to this states, # example n_weeks, can be stored as state.n_weeks hence changing the state of one # client does not affect the global n_week or the state of other clients. # Each time the on_change() is called, three arguments are passed in: # 1. state # 2. var_name, # 3. var_value # where the state is unique to that client that made the call. # Whenever a state of a client get changed, on_change() is called with three # params, this function is a special function in Taipy. n_weeks = 10 def read_data(dataset_path: str): df = pd.read_csv(dataset_path) df["Date"] = pd.to_datetime(df["Date"]) return df dataset = read_data("./dataset/dataset.csv") dataset_week = dataset[dataset["Date"].dt.isocalendar().week == n_weeks] def on_change(state, var_name: str, var_value): if var_name == "n_weeks": state.dataset_week = dataset[dataset["Date"].dt.isocalendar( ).week == var_value] page = """ # Taipy Basics *Week number*: *<|{n_weeks}|>* <|{n_weeks}|slider|min=3|max=52|> <|{dataset_week}|chart|type=bar|x=Date|y=Value|height=100%|width=100%|> """ Gui(page=page).run(dark_mode=False)
|
from taipy import Gui import pandas as pd # visual elements: Taipy adds visual elements on top of markdown # to give you the ability to add charts, tables... The format for # it is as follows: # <|{variable}|visual_element_name|param_1=param_1|param_2=param_2| ... |>. # variable: python variable eg dataframe # visual_element_name: Name of the visual element eg table # para_1: parameters passed in n_weeks = 10 def read_data(dataset_path: str): df = pd.read_csv(dataset_path) return df dataset = read_data("./dataset/dataset.csv") page = """ # Taipy Basics *Week number*: *<|{n_weeks}|>* <|{n_weeks}|slider|min=2|max=30|> <|{dataset[9000:]}|chart|type=bar|x=Date|y=Value|height=100%|> # Table Format <|{dataset}|table|height=400px|width=95%|> """ Gui(page=page).run(dark_mode=False)
|
from taipy import Gui # not no empty spaces at the beginning of the markdown # markdown must start from the baseline page = """ ### Hello world """ # Gui(page=page).run(dark_mode=False) # you can specify the port number in the run(port=xxxx) # its by default 5000 Gui(page="Intro to Taipy").run(dark_mode=True)
|
import taipy as tp from taipy import Scope, Config from taipy.core import Frequency import json from algos.algos import * # μ΄ μ½λλ μλ리μ€_cfg λ° νμ΄νλΌμΈ_csgλ₯Ό μμ±νλ μ½λμ
λλ€. # μ΄ λ λ³μλ κΈ°λ³Έ μ½λμμ μ μλ리μ€λ₯Ό λ§λλ λ° μ¬μ©λ©λλ€. # μ΄ μ½λλ μ€ν κ·Έλνλ₯Ό ꡬμ±ν κ²μ
λλ€. ############################################################################### # λ°μ΄ν°λ
Έλ ############################################################################### # 첫 λ²μ§Έ λ°μ΄ν° λ
Έλλ₯Ό μμ±ν©λλ€. μμ€λ csv νμΌμ
λλ€. path_to_demand = 'data/time_series_demand.csv' demand_cfg = Config.configure_data_node(id="demand", storage_type="csv", scope=Scope.SCENARIO, path=path_to_demand, has_header=True) fixed_variables_default_json = open('data/fixed_variables_default.json') fixed_variables_default = json.load(fixed_variables_default_json) # fixed_variables_defaultλ₯Ό κΈ°λ³Έ λ°μ΄ν°λ‘ νλ λ λ²μ§Έ λ°μ΄ν° λ
Έλ μμ± # μ΄κ²μ fixed_variableμ λν λ€λ₯Έ κ°μ μ μΆν λ μΈ μ΄ λ°μ΄ν° λ
Έλμ
λλ€. fixed_variables_cfg = Config.configure_data_node(id="fixed_variables", default_data = fixed_variables_default, scope=Scope.PIPELINE) # λͺ¨λΈμ μΆμ νλ λ°μ΄ν° λ
Έλλ λ€μκ³Ό κ°μ΅λλ€. model_created λ°μ΄ν° λ
Έλ, model_solved λ°μ΄ν° λ
Έλ model_created_cfg = Config.configure_data_node(id="model_created", scope=Scope.PIPELINE) model_solved_cfg = Config.configure_data_node(id="model_solved", scope=Scope.PIPELINE) # μ΄κ²μ λ©μΈ μ½λμμ κ²°κ³Όλ₯Ό μ»λ λ° μ¬μ©ν λ°μ΄ν° λ
Έλμ
λλ€. results_cfg = Config.configure_data_node(id="results", scope=Scope.PIPELINE) ############################################################################### # μμ
############################################################################### # (demand_cfg,fixed_variables_cfg) -> |create_model| -> (model_created_cfg) create_model_task = Config.configure_task(id="create_model", input=[demand_cfg,fixed_variables_cfg], function=create_model, output=[model_created_cfg]) # (model_created_cfg) -> |solve_model| -> (model_solved_cfg) solve_model_cfg = Config.configure_task(id="solve_model", input=[model_created_cfg], function=solve_model, output=[model_solved_cfg]) # (model_solved_cfg,fixed_variables_cfg,demand_cfg) -> |create_results| -> (results_cfg) create_results_cfg = Config.configure_task(id="create_results", input=[model_solved_cfg,fixed_variables_cfg,demand_cfg], function=create_results, output=[results_cfg]) ############################################################################### # νμ΄νλΌμΈ λ° μλλ¦¬μ€ κ΅¬μ± ############################################################################### # νμ΄νλΌμΈ : μμ
μ€ν. μΌλ ¨μ μμ
μ μννλ κ²μ λ§ν©λλ€. pipeline_cfg = Config.configure_pipeline(id="pipeline",task_configs=[create_model_task,solve_model_cfg,create_results_cfg]) # μλλ¦¬μ€ : νμ΄νλΌμΈ μ€ν. μΌλ ¨μ νμ΄νλΌμΈ(μ¬κΈ°μλ νλλ§)μ μ€νμ λνλ
λλ€. # μ΄ λ³μλ₯Ό ν΅ν΄ μλ‘μ΄ μλ리μ€λ₯Ό μμ±ν©λλ€. scenario_cfg = Config.configure_scenario(id="scenario",pipeline_configs=[pipeline_cfg], frequency=Frequency.MONTHLY)
|
import numpy as np import pandas as pd # μ΄ μ½λλ μμμ λν csv νμΌμ μμ±νλ λ° μ¬μ©λλ©° λ¬Έμ μ μμ€ λ°μ΄ν°μ
λλ€. def create_time_series(nb_months=12,mean_A=840,mean_B=760,std_A=96,std_B=72, amplitude_A=108,amplitude_B=144): time_series_A = [] time_series_A.append(mean_A) time_series_B = [] time_series_B.append(mean_B) for i in range(1,nb_months): time_series_A.append(np.random.normal(mean_A + amplitude_A*np.sin(2*np.pi*i/12),std_A)) time_series_B.append(np.random.normal(mean_B + amplitude_B*np.sin((2*np.pi*(i+6))/12),std_B)) time_series_A = pd.Series(time_series_A) time_series_B = pd.Series(time_series_B) month = [i%12 for i in range(nb_months)] year = [i//12 + 2020 for i in range(nb_months)] df_time_series = pd.DataFrame({"Year":year,"Month":month,"Demand_A":time_series_A,"Demand_B":time_series_B}) return df_time_series def time_series_to_csv(nb_months=12,mean_A=840,mean_B=760,std_A=96,std_B=72, amplitude_A=108,amplitude_B=144): time_serie_data = create_time_series(nb_months,mean_A,mean_B,std_A,std_B, amplitude_A,amplitude_B) time_serie_data.to_csv('data/time_series_demand.csv')
|
da_display_table_md = "<center>\n<|{ch_results.round()}|table|columns={list(chart.columns)}|width=fit-content|height={height_table}|></center>\n" d_chart_csv_path = None def da_create_display_table_md(str_to_select_chart): return "<center>\n<|{" + str_to_select_chart + \ "}|table|width=fit-content|height={height_table}|></center>\n" da_databases_md = """ # λ°μ΄ν° μμ€ <|layout|columns=3 2 1|columns[mobile]=1| <layout_scenario| <|layout|columns=1 1 3|columns[mobile]=1| <year| Year <|{sm_selected_year}|selector|lov={sm_year_selector}|dropdown|width=100%|on_change=change_sm_month_selector|> |year> <month| Month <|{sm_selected_month}|selector|lov={sm_month_selector}|dropdown|width=100%|on_change=change_scenario_selector|> |month> <scenario| Scenario <|{selected_scenario}|selector|lov={scenario_selector}|dropdown|value_by_id|width=18rem|> |scenario> |> |layout_scenario> <| **Table** \n \n <|{sm_graph_selected}|selector|lov={sm_graph_selector}|dropdown|> |> <br/> <br/> <|{d_chart_csv_path}|file_download|name=table.csv|label=Download table|> |> <|part|render={len(scenario_selector)>0}|partial={partial_table}|> <|part|render=False| <|{scenario_counter}|> |> """
|
import pandas as pd import json with open('data/fixed_variables_default.json', "r") as f: fixed_variables_default = json.load(f) # Taipy Coreμ μ½λλ μμ§ μ€νλμ§ μμμ΅λλ€. csv νμΌμ μ΄λ° μμΌλ‘ μ½μ΅λλ€. da_initial_demand = pd.read_csv('data/time_series_demand.csv') da_initial_demand = da_initial_demand[['Year', 'Month', 'Demand_A', 'Demand_B']].astype(int) da_initial_demand.columns = [col.replace('_', ' ') for col in da_initial_demand.columns] da_initial_variables = pd.DataFrame({key: [fixed_variables_default[key]] for key in fixed_variables_default.keys() if 'Initial' in key}) # μλ μ½λλ μ΄ μ΄λ¦μ νμμ μ¬λ°λ₯΄κ² μ§μ νλ κ²μ
λλ€. da_initial_variables.columns = [col.replace('_', ' ').replace('one', '1').replace('two', '2').replace('initial ', '') for col in da_initial_variables.columns] da_initial_variables.columns = [col[0].upper() + col[1:] for col in da_initial_variables.columns] da_data_visualisation_md = """ # λ°μ΄ν° μκ°ν <|Expand here|expanded=False|expandable| <|layout|columns=1 1 1|columns[mobile]=1| <| ## μ΄κΈ° μ¬κ³ <center> <|{da_initial_variables[[col for col in da_initial_variables.columns if 'Stock' in col]]}|table|show_all|width=445px|> </center> |> <| ## μ΄κΈ° μμ° <center> <|{da_initial_variables[[col for col in da_initial_variables.columns if 'Production' in col]]}|table|show_all|width=445px|> </center> |> <| ## ꡬ맀ν μλ£ <center> <|{da_initial_variables[[col for col in da_initial_variables.columns if 'Purchase' in col]]}|table|show_all|width=445px|> </center> |> |> ## λ€κ°μ€λ λ¬μ μμ <center> <|{da_initial_demand.round()}|table|width=fit-content|show_all|height=fit-content|> </center> |> ## μμμ μ§ν <|{da_initial_demand}|chart|x=Month|y[1]=Demand A|y[2]=Demand B|width=100%|> """
|
from data.create_data import time_series_to_csv from config.config import scenario_cfg from taipy.core import taipy as tp import datetime as dt import pandas as pd cc_data = pd.DataFrame( { 'Date': [dt.datetime(2021, 1, 1)], 'Cycle': [dt.date(2021, 1, 1)], 'Cost of Back Order': [0], 'Cost of Stock': [0] }) cc_show_comparison = False cc_layout = {'barmode': 'stack', 'margin': {"t": 20}} cc_creation_finished = False def cc_create_scenarios_for_cycle(): """μ΄ κΈ°λ₯μ μ¬λ¬ μ£ΌκΈ°μ λν μλ리μ€λ₯Ό μμ±νκ³ μ μΆν©λλ€. """ date = dt.datetime(2021, 1, 1) month = date.strftime('%b') year = date.strftime('%Y') current_month = dt.date.today().strftime('%b') current_year = dt.date.today().strftime('%Y') while month != current_month or year != current_year: date += dt.timedelta(days=15) month = date.strftime('%b') year = date.strftime('%Y') if month != current_month or year != current_year: time_series_to_csv( nb_months=12, mean_A=840, mean_B=760, std_A=96, std_B=72, amplitude_A=108, amplitude_B=144) name = f"Scenario {date.strftime('%d-%b-%Y')}" scenario = tp.create_scenario(scenario_cfg, creation_date=date, name=name) tp.submit(scenario) def update_cc_data(state): """μ΄ κΈ°λ₯μ λͺ¨λ μ£ΌκΈ°μ κΈ°λ³Έ μλ리μ€μ λν μ΄μ μ£Όλ¬Έ λ° μ¬κ³ λΉμ©μ λ°μ μ λ§λλλ€.""" all_scenarios = tp.get_primary_scenarios() dates = [] cycles = [] costs_of_back_orders = [] costs_of_stock = [] all_scenarios_ordered = sorted( all_scenarios, key=lambda x: x.creation_date.timestamp()) # delete? for scenario in all_scenarios_ordered: results = scenario.results.read() if results is not None: date_ = scenario.creation_date dates.append(date_) cycles.append(dt.date(date_.year, date_.month, 1)) # sum_costs_of_stock λ©νΈλ¦ μμ± bool_costs_of_stock = [c for c in results.columns if 'Cost' in c and 'Total' not in c and 'Stock' in c] sum_costs_of_stock = int(results[bool_costs_of_stock].sum(axis=1)\ .sum(axis=0)) # sum_costs_of_BO μ§ν μμ± bool_costs_of_BO = [c for c in results.columns if 'Cost' in c and 'Total' not in c and 'BO' in c] sum_costs_of_BO = int(results[bool_costs_of_BO].sum(axis=1)\ .sum(axis=0)) costs_of_back_orders.append(sum_costs_of_BO) costs_of_stock.append(sum_costs_of_stock) state.cc_data = pd.DataFrame({'Date': dates, 'Cycle': cycles, 'Cost of Back Order': costs_of_back_orders, 'Cost of Stock': costs_of_stock}) state.cc_show_comparison = True cc_compare_cycles_md = """ # μ¬μ΄ν΄ λΉκ΅ <center> <|Compare Cycles|button|on_action={update_cc_data}|> </center> <|part|render={cc_show_comparison}| <|Table|expanded=False|expandable| <center> <|{cc_data}|table|width=fit-content|> </center> |> ## λΉμ©μ μ§ν <|{cc_data}|chart|type=bar|x=Cycle|y[1]=Cost of Back Order|y[2]=Cost of Stock|layout={cc_layout}|width=100%|height=600|> |> """
|
from .chart_md import ch_chart_md, ch_layout_dict, ch_results from config.config import fixed_variables_default from taipy.gui import Icon def create_sliders(fixed_variables): """" μ΄κ²μ λ§€κ°λ³μμ λν μ¬λΌμ΄λλ₯Ό μ체μ μΌλ‘ μμ±νλ λ§€μ° λ³΅μ‘ν ν¨μμ
λλ€. μμΌλ‘ ν μλ μμμ΅λλ€. κ·Έλ¬λ μ΄ λ°©λ²μ μ₯κΈ°μ μΌλ‘ λ μ μ°ν©λλ€. """ # λ°νλ λ¬Έμμ΄ slider_md = "" # λ§€κ°λ³μμλ μΈ κ°μ§ μ νμ΄ μμ΅λλ€. param_types = ['Capacity Constraints','Objective Weights','Initial Parameters'] # λ€λ₯Έ μ νμ μ¬λΌμ΄λλ (ν κΈμ μ¬μ©νμ¬) λ€λ₯Έ μΉμ
μΌλ‘ κ·Έλ£Ήνλ©λλ€. products = ['FPA','FPB','RPone','RPtwo','weight'] for p_type in param_types: # p_typeμ΄ μ νλλ©΄ ν΄λΉ λΆλΆμ΄ νμλ©λλ€. slider_md += "\n<|part|render={pa_param_selected == '" + p_type + "'}|" if p_type != 'Objective Weights': # the part will be shown if 'Objective Weights' is not selected slider_md +=""" <center> <|{pa_product_param}|toggle|lov={pa_choice_product_param}|value_by_id|> </center> <br/> """ if p_type == 'Objective Weights': var_p = [key for key in fixed_variables.keys() if ('produce' not in key and 'Weight' in key)] # κ° λ³μ(var_p)μ λν΄ μ¬λΌμ΄λκ° μμ±λκ³ μμ΅λλ€. # μ΅μκ°κ³Ό μ΅λκ°λ μλμΌλ‘ μμ±λ©λλ€. for var in var_p : min_ = str(int(fixed_variables[var]*0.35)) max_ = str(int(fixed_variables[var]*1.65)) if fixed_variables[var] != 0 else '50' name_of_var = var.replace('cost','Unit Cost -') name_of_var = name_of_var[0].upper() + name_of_var[1:].replace('_',' ').replace('one','1').replace('two','2') slider_md += "\n\n" + name_of_var + " : *<|{fixed_variables."+var+"}|>*" slider_md += "\n<|{fixed_variables."+var+"}|slider|orientation=h|min="+min_+"|max="+max_+"|step=5|>" else : # μ νμ λ°λΌ λΆνμ΄ νμλ©λλ€. for p in products : slider_md += "\n<|part|render={pa_product_param == 'product_"+p+"'}|" if p_type == 'Capacity Constraints': var_p = [key for key in fixed_variables.keys() if (p in key and 'produce' not in key and 'Max' in key)] else : var_p = [key for key in fixed_variables.keys() if (p in key and 'produce' not in key and 'Capacity' not in key and 'Max' not in key)] # κ° λ³μ(var_p)μ λν΄ μ¬λΌμ΄λκ° μμ±λκ³ μμ΅λλ€. # μ΅μκ°κ³Ό μ΅λκ°λ μλμΌλ‘ μμ±λ©λλ€. for var in var_p : min_ = str(int(fixed_variables[var]*0.35)) max_ = str(int(fixed_variables[var]*1.65)) if fixed_variables[var] != 0 else '50' name_of_var = var.replace('cost','Unit Cost -') name_of_var = name_of_var[0].upper() + name_of_var[1:].replace('_',' ').replace('one','1').replace('two','2') slider_md += "\n\n" + name_of_var + " : *<|{fixed_variables."+var+"}|>*" slider_md += "\n<|{fixed_variables."+var+"}|slider|orientation=h|min="+min_+"|max="+max_+"|step=5|>" slider_md += "\n|>" slider_md+="\n|>" return slider_md pa_sliders_md = create_sliders(fixed_variables_default) pa_parameters_md = """ <|layout|columns=139 1 45|columns[mobile]=1|gap=1.5rem| """ + ch_chart_md + """ <blank_space| |blank_space> <| <center> <|{pa_param_selected}|selector|lov={pa_param_selector}|> </center> """ + pa_sliders_md + """ <|Delete|button|on_action={delete_scenario_fct}|active={len(scenario_selector)>0}|id=delete_button|> <|Make Primary|button|on_action={make_primary}|active={len(scenario_selector)>0 and not selected_scenario_is_primary}|id=make_primary|> <|Re-optimize|button|on_action=submit_scenario|active={len(scenario_selector)>0}|id=re_optimize|> <|New scenario|button|on_action=create_new_scenario|id=new_scenario|> |> |> """ pa_param_selector = ['Capacity Constraints','Objective Weights','Initial Parameters'] pa_param_selected = pa_param_selector[0] # μ¬λΌμ΄λ μ ν ν κΈ pa_choice_product_param = [("product_RPone", Icon("images/P1.png", "product_RPone")), ("product_RPtwo", Icon("images/P2.png", "product_RPtwo")), ("product_FPA", Icon("images/PA.png", "product_FPA")), ("product_FPB", Icon("images/PB.png", "product_FPB"))] pa_product_param = 'Else'
|
from taipy.gui import Icon import pandas as pd ch_layout_dict = {"margin":{"t":20}} # μ°¨νΈ μ€μ ν κΈ ch_choice_chart = [("pie", Icon("images/pie.png", "pie")), ("chart", Icon("images/chart.png", "chart"))] ch_show_pie = ch_choice_chart[1][0] ch_results = pd.DataFrame({"Monthly Production FPA":[], "Monthly Stock FPA": [], "Monthly BO FPA": [], "Max Capacity FPA": [], "Monthly Production FPB": [], "Monthly Stock FPB": [], "Monthly BO FPB": [], "Max Capacity FPB": [], "Monthly Stock RP1":[], "Monthly Stock RP2":[], "Monthly Purchase RP1":[], "Monthly Purchase RP2":[], "Demand FPA": [], "Demand FPB": [], 'Stock FPA Cost': [], 'Stock FPB Cost': [], 'Stock RP1 Cost': [], 'Stock RP2 Cost': [], 'Purchase RP1 Cost': [], 'Purchase RP2 Cost': [], "BO FPA Cost":[], "BO FPB Cost":[], "Total Cost": [], "index": []}) def get_col(ch_results:pd.DataFrame,var:str): if var == 'Cost': columns = [col for col in ch_results.columns if var in col] elif var=='Production': columns = [col for col in ch_results.columns if (var in col or 'Capacity' in col) and 'Cost' not in col] else : columns = [col for col in ch_results.columns if var in col and 'Cost' not in col] return columns def get_y_format(columns): md ="" for col_i in range(len(columns)): md+=f"y[{col_i+1}]={columns[col_i]}|" if "Capacity" in columns[col_i] : md+=f"line[{col_i+1}]=dash|" return md[:-1] def create_charts_md(ch_results): """" μ΄κ²μ λͺ¨λ μ°¨νΈλ₯Ό μμ±νλ λ§€μ° λ³΅μ‘ν ν¨μμ
λλ€. λν μ¬μ©μ μμ
μ λ°λΌ μκ°μ΄ μ§λ¨μ λ°λΌ λ³κ²½λλ λ¨μΌ λ¬Έμμ΄μ κ°λλ‘ μλμΌλ‘ μννκ±°λ λΆλΆμ μΌλ‘ μ¬μ©ν μ μμ΅λλ€. """ # μ°¨νΈμ© mdλ₯Ό λ§λλ λ§€κ°λ³μ config_scenario_option = ["sm_show_config_scenario", "not(sm_show_config_scenario)"] # νμ΄λ μ΄λ¬ν ννμ κ°λ₯ν©λλ€. pie_possible = ['Costs','Purchases','Productions','Stocks','Back Order'] charts_option_for_col = ['Cost','Purchase','Production','Stock','BO','FPA','FPB','RP1','RP2'] charts_option = ['Costs','Purchases','Productions','Stocks','Back Order','Product FPA','Product FPB','Product RP1','Product RP2'] md = "" for config_scenario in config_scenario_option : md += "\n<|part|render={"+config_scenario+"}|" md += "\n<|" for charts_i in range(len(charts_option)): columns = get_col(ch_results,charts_option_for_col[charts_i]) y_format = get_y_format(columns) columns = [c for c in columns if 'Total' not in c] # in the pie, we don't want to show the total if charts_option[charts_i] in pie_possible : md +="\n<|{pie_results.loc[" + str(columns) + "]}|chart|type=pie|x=values|label=labels|width={width_chart}|height={height_chart}|layout={ch_layout_dict}|render={ch_show_pie=='pie' and sm_graph_selected=='"+charts_option[charts_i]+"'}|>" md += "\n<|{ch_results}|chart|x=index|" + y_format + "|width={width_chart}|height={height_chart}|layout={ch_layout_dict}|render={ch_show_pie=='chart' and sm_graph_selected=='"+charts_option[charts_i]+"'}|>" else: md += "\n<|{ch_results}|chart|x=index|" + y_format + "|width={width_chart}|height={height_chart}|layout={ch_layout_dict}|render={sm_graph_selected=='"+charts_option[charts_i]+"'}|>" md += """\n|> |>""" return md ch_chart_md_1 = """ <br/> <|layout|columns=1 1|columns[mobile]=1| <| <center> <|{str(int(sum_costs_of_BO/1000))+' K'}|indicator|value={sum_costs_of_BO}|min=50_000|max=1_000|width=93%|> Back Order Cost </center> |> <| <center> <|{str(int(sum_costs_of_stock/1000))+' K'}|indicator|value={sum_costs_of_stock}|min=100_000|max=25_000|width=93%|> Stock Cost </center> |> |> """ ch_chart_md = """ <| <|part|render={len(scenario_selector)>0}| <|""" + ch_chart_md_1 + """|> """ + create_charts_md(ch_results) + """ |> <no_scenario|part|render={len(scenario_selector)==0}| ## No scenario created for the current month |no_scenario> |> """
|
import taipy as tp from taipy.gui import Icon import datetime as dt import os import hashlib import json login = '' password = '' dialog_login = False dialog_new_account = False new_account = False all_scenarios = tp.get_scenarios() users = {} json.dump(users, open('login/login.json', 'w')) dialog_user = True user_selector = [('Create new user',Icon('/images/new_account.png','Create new user'))] user_in_session = '' selected_user = None salt = os.urandom(32) def open_dialog_user(state): state.login = '' state.dialog_user = True def encode(password): key = str(hashlib.pbkdf2_hmac( 'sha256', # The hash digest algorithm for HMAC password.encode('utf-8'), # Convert the password to bytes salt, # Provide the salt 100000, # It is recommended to use at least 100,000 iterations of SHA-256 dklen=128 # Get a 128 byte key )) return key def test_password(users, login, new_password): old_key = users[login]['password'] new_key = str(hashlib.pbkdf2_hmac( 'sha256', # The hash digest algorithm for HMAC new_password.encode('utf-8'), # Convert the password to bytes salt, # Provide the salt 100000, # It is recommended to use at least 100,000 iterations of SHA-256 dklen=128 # Get a 128 byte key )) return old_key == new_key def detect_inactive_session(state): users[state.login]['last_visit'] = str(dt.datetime.now()) json.dump(users, open('login/login.json', 'w')) for user in users.keys(): if (dt.datetime.now() - dt.datetime.strptime(users[user]['last_visit'], '%Y-%m-%d %H:%M:%S.%f')).seconds >= 6 * 3600: [tp.delete(s.id) for s in tp.get_scenarios() if 'user' in s.properties and users[user] == s.properties['user']] users.pop(user) login_md = """ <|part|id=part_dialog_button| Welcome, <|{login if login != '' else 'login'}|button|on_action={open_dialog_user}|id=dialog_button|>! |> <|{dialog_user}|dialog|title=Set account|id=dialog_user|width=20%| <|{selected_user}|selector|lov={user_selector}|on_change=on_change_user_selector|id=user_selector|width=100%|value_by_id|> |> <|{dialog_login}|dialog|title=Login|on_action=validate_login|labels=Cancel; Login|id=dialog_user|width=20%| <|{selected_user}|selector|lov={[(login, Icon('/images/user.png', login))]}|id=user_selected|width=100%|value_by_id|> Password <|{password}|input|password=True|> |> <|{dialog_new_account}|dialog|title=Register|on_action=validate_login|labels=Cancel; Register|id=dialog_user|width=20%| Username <|{login}|input|> Password <|{password}|input|password=True|> |> <|part|render={1==0}| <|{user_in_session}|> |> """
|
from taipy import Gui page = """ # Hello World π with *Taipy* This is my first Taipy test app. And it is running fine! """ Gui(page).run(use_reloader=True) # use_reloader=True if you are in development
|
from taipy import Gui from page.dashboard_fossil_fuels_consumption import * if __name__ == "__main__": Gui(page).run( use_reloader=True, title="Test", dark_mode=False, ) # use_reloader=True if you are in development
|
import pandas as pd import taipy as tp from data.data import dataset_fossil_fuels_gdp country = "Spain" region = "Europe" lov_region = list(dataset_fossil_fuels_gdp.Entity.unique()) def load_dataset(_country): """Load dataset for a specific country. Args: _country (str): The name of the country. Returns: pandas.DataFrame: A DataFrame containing the fossil fuels GDP data for the specified country. """ dataset_fossil_fuels_gdp_cp = dataset_fossil_fuels_gdp.reset_index() dataset_fossil_fuels_gdp_cp = dataset_fossil_fuels_gdp_cp[ dataset_fossil_fuels_gdp["Entity"] == _country ] return dataset_fossil_fuels_gdp_cp dataset_fossil_fuels_gdp_cp = load_dataset(country) def on_change_country(state): """Update the dataset based on the selected country. Args: state (object): The "state" of the variables ran by the program (value changes through selectors) Returns: None """ print("country is:", state.country) _country = state.country dataset_fossil_fuels_gdp_cp = load_dataset(_country) state.dataset_fossil_fuels_gdp_cp = dataset_fossil_fuels_gdp_cp layout = {"yaxis": {"range": [0, 100000]}, "xaxis": {"range": [1965, 2021]}} page = """ # Fossil Fuel consumption by per capita by country* Data comes from <a href="https://ourworldindata.org/grapher/per-capita-fossil-energy-vs-gdp" target="_blank">Our World in Data</a> <|{country}|selector|lov={lov_region}|on_change=on_change_country|dropdown|label=Country/Region|> <|{dataset_fossil_fuels_gdp_cp}|chart|type=plot|x=Year|y=Fossil fuels per capita (kWh)|height=200%|layout={layout}|> ## Fossil fuel per capita for <|{country}|>: <|{dataset_fossil_fuels_gdp_cp}|table|height=400px|width=95%|> """
|
import pandas as pd dataset_fossil_fuels_gdp = pd.read_csv("data/per-capita-fossil-energy-vs-gdp.csv") country_codes = pd.read_csv("./data/country_codes.csv") dataset_fossil_fuels_gdp = dataset_fossil_fuels_gdp.merge( country_codes[["alpha-3", "region"]], how="left", left_on="Code", right_on="alpha-3" ) dataset_fossil_fuels_gdp = dataset_fossil_fuels_gdp[ ~dataset_fossil_fuels_gdp["Fossil fuels per capita (kWh)"].isnull() ].reset_index() dataset_fossil_fuels_gdp["Fossil fuels per capita (kWh)"] = ( dataset_fossil_fuels_gdp["Fossil fuels per capita (kWh)"] * 1000 )
|
from taipy.gui import Gui as tpGui from taipy.gui import notify as tpNotify import pandas as pd text = "Original text" col1 = "first col" col2 = "second col" col3 = "third col" ballon_img = "./img/Ballon_15_20.png" section_1 = """ <h1 align="center">Getting started with Taipy GUI</h1> <|layout|columns=1 2 2| <| My text: <|{text}|> <|{text}|input|> |> <| <center> <|Press Me|button|on_action=on_button_action|> **Ein Button:** <|{col1}|> </center> |> <| <center> <|{ballon_img}|image|height=30%|width=30%|label=This is one ballon|> </center> |> |> """ section_2 = ''' ##Darstellung Gas-Verbrauch <|{dataset}|chart|mode=line|x=Datum|y[1]=Verbrauch|y[2]=Betriebsstunden|yaxis[2]=y2|layout={layout}|color[1]=green|color[2]=blue|> ''' layout = { "xaxis": { # Force the title of the x axis "title": "Time-Range" }, "yaxis": { # Force the title of the first y axis "title": "Verbrauch", # Place the first axis on the left "side": "left" }, "yaxis2": { # Second axis overlays with the first y axis "overlaying": "y", # Place the second axis on the right "side": "right", # and give it a title "title": "Betriebsstunden" }, "legend": { # Place the legend above chart "yanchor": "middle" } } def on_button_action(state): tpNotify(state, 'info', f'The text is: {state.text}') state.text = "Button Pressed" def on_change(state, var_name, var_value): if var_name == "text" and var_value == "Reset": state.text = "" return def get_data(path: str): dataset = pd.read_csv(path) dataset["Datum"] = pd.to_datetime(dataset["Datum"], dayfirst=True).dt.date return dataset gui = tpGui(page=section_1 + section_2) dataset = get_data("./dataset.csv") if __name__ == '__main__': # Execute by the _Python_ interpretor, for debug only. tpGui.run(gui, title="Taipy Demo", use_reloader=True, dark_mode=True, port=5001, flask_log=False) else: # Execute by _Gunicorn_, for production environment. app = tpGui.run(gui, title="Taipy Demo", run_server=False)
|
import os import logging from opentelemetry import metrics from opentelemetry import trace from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.resources import Resource, SERVICE_NAME from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import ( BatchSpanProcessor, ) logging.basicConfig(level=logging.DEBUG) service_name = os.environ.get("OTEL_SERVICE_NAME", __file__) otel_endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "localhost:4317") resource = Resource(attributes={SERVICE_NAME: service_name}) ###### Metrics metrics_reader = PeriodicExportingMetricReader( OTLPMetricExporter(endpoint=otel_endpoint) ) metrics_provider = MeterProvider(metric_readers=[metrics_reader], resource=resource) # Set the global default metrics provider metrics.set_meter_provider(metrics_provider) ###### Traces trace_provider = TracerProvider() processor = BatchSpanProcessor(OTLPSpanExporter(endpoint=otel_endpoint)) trace_provider.add_span_processor(processor) # Sets the global default tracer provider trace.set_tracer_provider(trace_provider) meter = metrics.get_meter_provider().get_meter("my.meter.name") tracer = trace.get_tracer("my.tracer.name") def init_metrics() -> dict: """Initializes metrics""" scenario_execution_counter = meter.create_counter( "scenario_execution", unit="counts", description="Counts the total number of times we execute a scenario", ) rec_svc_metrics = {"scenario_execution_counter": scenario_execution_counter} return rec_svc_metrics
|
import time from pathlib import Path from taipy import Config, Status import taipy as tp from taipy.gui import get_state_id, invoke_callback from metrics import init_metrics, tracer # Telemetry rec_svc_metrics = init_metrics() @tracer.start_as_current_span("function_double") def double(nb): """Double the given number.""" time.sleep(1) return int(nb) * 2 Config.load(Path(__file__).parent / "config.toml") SCENARIO = Config.scenarios["my_scenario"] # pylint: disable=no-member value = 21 # pylint: disable=invalid-name result = double(value) # pylint: disable=invalid-name CONTENT = """ * You can double this number: <|{value}|input|propagate=True|> * by clicking on this button: <|Double it!|button|on_action=on_button_click|> * and here is the result: <|{result}|> """ gui = tp.Gui(page=CONTENT) core = tp.Core() def job_updated(state_id, scenario, job): """Callback called when a job has been updated.""" if job.status == Status.COMPLETED: def _update_result(state, output): state.result = output.read() # invoke_callback allows to run a function with a GUI _state_. invoke_callback(gui, state_id, _update_result, args=[scenario.output]) # Telemetry rec_svc_metrics["scenario_execution_counter"].add( 1, {"execution_type": "manual", "scenario_name": scenario.config_id} ) def on_button_click(state): """callback for button clicked""" state_id = get_state_id(state) my_scenario = tp.create_scenario(SCENARIO) my_scenario.input.write(state.value) tp.subscribe_scenario(scenario=my_scenario, callback=job_updated, params=[state_id]) tp.submit(my_scenario) if __name__ == "__main__": tp.run( gui, core, host="0.0.0.0", title="Basic Taipy App", )
|
from taipy.gui import Gui from tensorflow.keras import models from PIL import Image import numpy as np class_names = { 0: 'airplane', 1: 'automobile', 2: 'bird', 3: 'cat', 4: 'deer', 5: 'dog', 6: 'frog', 7: 'horse', 8: 'ship', 9: 'truck', } model = models.load_model("baseline_mariya.keras") def predict_image(model, path_to_img): img = Image.open(path_to_img) img = img.convert("RGB") img = img.resize((32, 32)) data = np.asarray(img) # print("before:",data[0][0]) data = data / 255 # print("after:",data[0][0]) probs = model.predict(np.array([data])[:1]) # print(probs) # print(probs.max()) top_prob = probs.max() # print(np.argmax(probs)) top_pred = class_names[np.argmax(probs)] return top_prob, top_pred content = "" img_path = "placeholder_image.png" prob = 0 pred = "" index = """ <|text-center| <|{"logo.png"}|image|width = 25vw|> <|{content}|file_selector|extensions = .png|> select an image from your file system <|{pred}|> <|{img_path}|image|> <|{prob}|indicator|value = {prob}|min = 0|max = 100|width = 25vw|> |> """ def on_change(state, var_name, var_val): if var_name == "content": top_prob, top_pred = predict_image(model, var_val) state.prob = round(top_prob * 100) state.pred = "This is a " + top_pred state.img_path = var_val # print(var_name,var_val) app = Gui(page=index) if __name__ == "__main__": app.run()
|
def a
|
import os import threading from flask import Flask from pyngrok import ngrok from hf_hub_ctranslate2 import GeneratorCT2fromHfHub from flask import request, jsonify model_name = "taipy5-ct2" # note this is local folder model, the model uploaded to huggingface did not response correctly #model_name = "michaelfeil/ct2fast-starchat-alpha" #model_name = "michaelfeil/ct2fast-starchat-beta" model = GeneratorCT2fromHfHub( # load in int8 on CUDA model_name_or_path=model_name, device="cuda", compute_type="int8_float16", # tokenizer=AutoTokenizer.from_pretrained("{ORG}/{NAME}") ) def generate_text_batch(prompt_texts, max_length=64): outputs = model.generate(prompt_texts, max_length=max_length, include_prompt_in_result=False) return outputs app = Flask(__name__) port = "5000" # Open a ngrok tunnel to the HTTP server public_url = ngrok.connect(port).public_url print(" * ngrok tunnel \"{}\" -> \"http://127.0.0.1:{}\"".format(public_url, port)) # Update any base URLs to use the public ngrok URL app.config["BASE_URL"] = public_url # ... Update inbound traffic via APIs to use the public-facing ngrok URL # Define Flask routes @app.route("/") def index(): return "Hello from Colab!" @app.route("/api/generate", methods=["POST"]) def generate_code(): try: # Get the JSON data from the request body data = request.get_json() # Extract 'inputs' and 'parameters' from the JSON data inputs = data.get('inputs', "") parameters = data.get('parameters', {}) # Extract the 'max_new_tokens' parameter max_new_tokens = parameters.get('max_new_tokens', 64) # Call the generate_text_batch function with inputs and max_new_tokens generated_text = generate_text_batch([inputs], max_new_tokens)[0] return jsonify({ "generated_text": generated_text, "status": 200 }) except Exception as e: return jsonify({"error": str(e)}) # Start the Flask server in a new thread threading.Thread(target=app.run, kwargs={"use_reloader": False}).start()
|
#Imports from taipy.gui import Gui from tensorflow.keras import models from PIL import Image import numpy as np #Variables classes = { 0: 'airplane', 1: 'automobile', 2: 'bird', 3: 'cat', 4: 'deer', 5: 'dog', 6: 'frog', 7: 'horse', 8: 'ship', 9: 'truck' } model = models.load_model("baseline_model.keras") content="" img_path = 'placeholder_image.png' prob = 0 pred = "" #Define model prediction function def predict_image(model, path): img = Image.open(path) img = img.convert("RGB") img = img.resize((32, 32)) data = np.asarray(img) data = data / 255 data = np.array([data]) probs = model.predict(data) top_prob = probs.max() top_pred = classes.get(np.argmax(probs)) return top_prob, top_pred #Define the app as a Gui index = """ <|text-center| <|{"logo.png"}|image|> <|{content}|file_selector|extensions=.png|> Select an image to classify <|{pred}|> <|{img_path}|image|> <|{prob}|indicator|value={prob}|min=0|max=100|width=22vw|> > """ def on_change(state, var, val): if var == "content": top_prob, top_pred = predict_image(model, val) state.img_path = val state.prob = round(top_prob * 100) state.pred = f"This is a {top_pred}" #print(state,var,val) app = Gui(page = index) #Run script if __name__ =="__main__": app.run(use_reloader=True)
|
from taipy.gui import Gui, notify import pandas as pd import webbrowser import datetime import os DOWNLOAD_PATH = "data/download.csv" upload_file = None section_1 = """ <center> <|navbar|lov={[("page1", "This Page"), ("https://docs.taipy.io/en/latest/manuals/about/", "Taipy Docs"), ("https://docs.taipy.io/en/latest/getting_started/", "Getting Started")]}|> </center> Data Dashboard with Taipy ========================= <|layout|columns=1 3| <| ### Let's create a simple Data Dashboard! <br/> <center> <|{upload_file}|file_selector|label=Upload Dataset|> </center> |> <| <center> <|{logo}|image|height=250px|width=250px|on_action=image_action|> </center> |> |> """ section_2 = """ ## Data Visualization <|{dataset}|chart|mode=lines|x=Date|y[1]=MinTemp|y[2]=MaxTemp|color[1]=blue|color[2]=red|> """ section_3 = """ <|layout|columns= 1 5| <| ## Custom Parameters **Starting Date**\n\n<|{start_date}|date|not with_time|on_change=start_date_onchange|> <br/><br/> **Ending Date**\n\n<|{end_date}|date|not with_time|on_change=end_date_onchange|> <br/> <br/> <|button|label=GO|on_action=button_action|> |> <| <center> <h2>Dataset</h2><|{DOWNLOAD_PATH}|file_download|on_action=download|> <|{dataset}|table|page_size=10|height=500px|width=65%|> </center> |> |> """ def image_action(state): webbrowser.open("https://taipy.io") def get_data(path: str): dataset = pd.read_csv(path) dataset["Date"] = pd.to_datetime(dataset["Date"]).dt.date return dataset def start_date_onchange(state, var_name, value): state.start_date = value.date() def end_date_onchange(state, var_name, value): state.end_date = value.date() def filter_by_date_range(dataset, start_date, end_date): mask = (dataset['Date'] > start_date) & (dataset['Date'] <= end_date) return dataset.loc[mask] def button_action(state): state.dataset = filter_by_date_range(dataset, state.start_date, state.end_date) notify(state, "info", "Updated date range from {} to {}.".format(state.start_date.strftime("%m/%d/%Y"), state.end_date.strftime("%m/%d/%Y"))) def download(state): state.dataset.to_csv(DOWNLOAD_PATH) logo = "images/taipy_logo.jpg" dataset = get_data("data/weather.csv") start_date = datetime.date(2008, 12, 1) end_date = datetime.date(2017, 6, 25) gui = Gui(page=section_1+section_2+section_3) if __name__ == '__main__': # the options in the gui.run() are optional, try without them gui.run(title='Taipy Demo GUI 2', host='0.0.0.0', port=os.environ.get('PORT', '5050'), dark_mode=False) else: app = gui.run(title='Taipy Demo GUI 2', dark_mode=False, run_server=False)
|
from taipy.gui import Gui from pages.all_regions import * from pages.by_region import * # Toggle theme: switch dark/light mode root_md = """ <|toggle|theme|> <center>\n<|navbar|>\n</center> """ stylekit = { "color-primary": "#CC3333", "color-secondary": "#E0C095", "color-background-light": "#F7E7CE", "color-background-dark": "#E0C095", } pages = {"/": root_md, "all_regions": all_regions_md, "by_region": by_region_md} gui_multi_pages = Gui(pages=pages) if __name__ == "__main__": gui_multi_pages.run( use_reloader=True, title="Wine π· production by Region and Year", dark_mode=False, stylekit=stylekit, )
|
import geopandas as gpd import pandas as pd def add_basic_stats(df_wine: pd.DataFrame) -> pd.DataFrame: """Add basic statistics to a DataFrame containing wine production data. This function calculates the minimum, maximum, and average wine production values for each row in the input DataFrame based on yearly data. The resulting DataFrame includes three additional columns: 'min', 'max', and 'average'. Args: df_wine (pd.DataFrame): A DataFrame containing wine production data for various French wine regions. Returns: df_wine_with_stats (pd.DataFrame): A new DataFrame with additional columns ('min', 'max', 'average') representing the calculated statistics for each row. """ df_wine_with_stats = df_wine.copy() df_wine_years = df_wine_with_stats[ [ "08/09", "09/10", "10/11", "11/12", "12/13", "13/14", "14/15", "15/16", "16/17", "17/18", "18/19", ] ] df_wine_with_stats["min"] = df_wine_years.min(axis=1) df_wine_with_stats["max"] = df_wine_years.max(axis=1) df_wine_with_stats["average"] = round(df_wine_years.mean(axis=1), 2) # Rename the "wine_basin" column for better readability in the dashboard df_wine_with_stats = df_wine_with_stats.rename(columns={"wine_basin": "Region"}) return df_wine_with_stats def add_geometry( df_wine_with_stats: pd.DataFrame, geometry: pd.DataFrame ) -> pd.DataFrame: """Add geographical information to a DataFrame containing wine production statistics. This function takes a DataFrame with wine production statistics (`df_wine_with_stats`) and a DataFrame with geographical information (`geometry`). It adds geographical data to the wine production DataFrame (including latitude and longitude). Args: df_wine_with_stats (pd.DataFrame): DataFrame containing wine production statistics for various regions and wine types. geometry (pd.DataFrame): DataFrame with geometrical information, including the 'geometry' column containing the geographical shapes. Returns: df_wine_with_geometry (pd.DataFrame): A new DataFrame with additional geographical information, including latitude and longitude, added to the wine production data. """ df_geometry = gpd.GeoDataFrame.from_features(geometry, crs=3857) # Reproject to EPSG:4326 to be able to extract Lon and Lat df_geometry = df_geometry.to_crs(epsg=4326) df_wine_with_geometry = df_wine_with_stats.copy() # Drop the rows that are subsets (so we don't count in aggregation) rows_to_drop = df_wine_with_geometry["AOC"].str.contains("(subset)") df_wine_with_geometry = df_wine_with_geometry.drop( df_wine_with_geometry[rows_to_drop].index ) df_wine_with_geometry = df_wine_with_geometry.reset_index(drop=True) # Drop the "AOC" column, as well as "min" and "max" df_wine_with_geometry = df_wine_with_geometry.drop(["AOC", "min", "max"], axis=1) df_wine_with_geometry = df_wine_with_geometry.groupby(["Region", "wine_type"]).sum() df_wine_with_geometry = df_wine_with_geometry.reset_index() df_wine_with_geometry = df_wine_with_geometry.sort_values( by=["average"], ascending=False ).reset_index(drop=True) # Extract latitude and longitude df_geometry["latitude"] = df_geometry["geometry"].y df_geometry["longitude"] = df_geometry["geometry"].x df_geometry = df_geometry.drop("geometry", axis=1) df_wine_with_geometry = pd.merge( df_wine_with_geometry, df_geometry, left_on="Region", right_on="Bassin" ) df_wine_with_geometry = df_wine_with_geometry.drop("Bassin", axis=1) return df_wine_with_geometry
|
import taipy.core as tp from taipy import Config # Loading of the TOML Config.load("config/taipy-config.toml") tp.Core().run() # Get the scenario configuration scenario_cfg = Config.scenarios["SC_WINE"] sc_wine = tp.create_scenario(scenario_cfg) sc_wine.submit() df_wine_production = sc_wine.WINE_PRODUCTION_WITH_STATS.read() df_wine_with_geometry = sc_wine.WINE_PRODUCTION_WITH_GEOMETRY.read()
|
from typing import Any, Tuple import pandas as pd from config.config import df_wine_with_geometry list_of_regions = df_wine_with_geometry["Region"].unique().tolist() selected_region = "SUD-OUEST" def clean_df_region_color(df_region_color: pd.DataFrame) -> pd.DataFrame: """Clean and transform a DataFrame containing region color information. This function takes a DataFrame (`df_region_color`) containing color information for a specific wine region. It performs cleaning operations, including dropping unnecessary columns and transposing the DataFrame for better representation. Args: df_region_color (pd.DataFrame): DataFrame containing color information for a specific wine region. Returns: pd.DataFrame: A cleaned and transformed DataFrame with columns 'Harvest' and 'years'. """ df_region_color_clean = df_region_color.drop( ["Region", "wine_type", "average", "latitude", "longitude"], axis=1 ) years = df_region_color_clean.columns df_region_color_clean = df_region_color_clean.transpose().rename( columns={0: "Harvest"} ) df_region_color_clean["Harvest"] = df_region_color_clean["Harvest"] / 10 df_region_color_clean["years"] = years return df_region_color_clean def create_df_region(selected_region: str) -> Tuple[pd.DataFrame, pd.DataFrame]: """Create DataFrames for red and white wine production statistics for a selected region. This function takes a selected region (`selected_region`) and extracts relevant information from the original wine production DataFrame (`df_wine_with_geometry`). It creates separate DataFrames for red and white wine production, applying additional cleaning operations. Args: selected_region (str): The selected wine region. Returns: Tuple[pd.DataFrame, pd.DataFrame]: A tuple containing two DataFrames - one for red wine ('df_region_red') and one for white wine ('df_region_white'). """ df_region = df_wine_with_geometry.copy() df_region = df_region[df_region["Region"] == selected_region] df_region_red = df_region[df_region["wine_type"] == "RED AND ROSE"].reset_index( drop=True ) df_region_white = df_region[df_region["wine_type"] == "WHITE"].reset_index( drop=True ) if selected_region not in ("CHAMPAGNE", "ALSACE ET EST"): df_region_red = clean_df_region_color(df_region_red) else: df_region_red = pd.DataFrame.from_dict( { "Harvest": [0] * 10, "years": [ "08/09", "09/10", "10/11", "11/12", "12/13", "13/14", "14/15", "15/16", "17/18", "18/19", ], } ) df_region_white = clean_df_region_color(df_region_white) return (df_region_red, df_region_white) df_region_red, df_region_white = create_df_region(selected_region) def on_change_region(state: Any) -> None: """Update red and white wine DataFrames based on a change in the selected region. This function takes the current state (`state`) and updates the red and white wine DataFrames (`df_region_red` and `df_region_white`) based on a change in the selected region. Args: state (Any): The current state object. Returns: None """ state.df_region_red, state.df_region_white = create_df_region(state.selected_region) ############################################################################################################## ## Chart properties: ## ############################################################################################################## plot_chart_layout = {"yaxis": {"range": [0, 600]}} property_plot_white = { "type": "scatter", "mode": "lines", "x": "years", "y": "Harvest", "color": "#E0C095", "title": f"Production of White wines (Million Liters)", } property_plot_red = { "type": "scatter", "mode": "lines", "x": "years", "y": "Harvest", "color": "#900020", "title": f"Production of Red wines (Million Liters)", } ############################################################################################################## ## Taipy Code: ## ############################################################################################################## by_region_md = """ <|layout|columns= 1 2| <|{selected_region}|selector|lov={list_of_regions}|on_change=on_change_region|dropdown|label=Choose Region|> # Wine production | **by Region**{: .color-primary} |> # Charts: <|layout|columns= 1 1| <|{df_region_red}|chart|properties={property_plot_red}|layout={plot_chart_layout}|> <|{df_region_white}|chart|properties={property_plot_white}|layout={plot_chart_layout}|> |> """
|
import numpy as np from taipy.gui import Gui from pages.country import country_md, on_change_country,\ selected_representation, data_country_date, pie_chart from pages.world import world_md from pages.map import map_md from pages.predictions import predictions_md, selected_scenario, result, scenario_country, scenario_date from data.data import data selector_country = list(np.sort(data['Country/Region'].astype(str).unique())) selected_country = 'France' pages = { "/":"<center><|navbar|></center>", "Country":country_md, "World":world_md, "Map":map_md, "Predictions":predictions_md } if __name__ == '__main__': gui_multi_pages = Gui(pages=pages) gui_multi_pages.run(title="Covid Dashboard", dark_mode=False, use_reloader=False, port=5039)
|
from taipy.config import Config, Scope import datetime as dt from algos.algos import add_features, create_train_data, preprocess,\ train_arima, train_linear_regression,\ forecast, forecast_linear_regression,\ result #Config.configure_job_executions(mode="standalone", nb_of_workers=2) path_to_data = "data/covid-19-all.csv" initial_data_cfg = Config.configure_data_node(id="initial_data", storage_type="csv", path=path_to_data, cacheable=True, validity_period=dt.timedelta(days=5), scope=Scope.GLOBAL) country_cfg = Config.configure_data_node(id="country", default_data="France", cacheable=True, validity_period=dt.timedelta(days=5)) date_cfg = Config.configure_data_node(id="date", default_data=dt.datetime(2020,10,1), cacheable=True, validity_period=dt.timedelta(days=5)) final_data_cfg = Config.configure_data_node(id="final_data", cacheable=True, validity_period=dt.timedelta(days=5)) train_data_cfg = Config.configure_data_node(id="train_data", cacheable=True, validity_period=dt.timedelta(days=5)) task_preprocess_cfg = Config.configure_task(id="task_preprocess_data", function=preprocess, input=[initial_data_cfg, country_cfg, date_cfg], output=[final_data_cfg,train_data_cfg]) model_cfg = Config.configure_data_node(id="model", cacheable=True, validity_period=dt.timedelta(days=5), scope=Scope.PIPELINE) task_train_cfg = Config.configure_task(id="task_train", function=train_arima, input=train_data_cfg, output=model_cfg) predictions_cfg = Config.configure_data_node(id="predictions", scope=Scope.PIPELINE) task_forecast_cfg = Config.configure_task(id="task_forecast", function=forecast, input=model_cfg, output=predictions_cfg) result_cfg = Config.configure_data_node(id="result", scope=Scope.PIPELINE) task_result_cfg = Config.configure_task(id="task_result", function=result, input=[final_data_cfg, predictions_cfg, date_cfg], output=result_cfg) pipeline_preprocessing_cfg = Config.configure_pipeline(id="pipeline_preprocessing", task_configs=[task_preprocess_cfg]) pipeline_arima_cfg = Config.configure_pipeline(id="ARIMA", task_configs=[task_train_cfg, task_forecast_cfg, task_result_cfg]) task_train_cfg = Config.configure_task(id="task_train_linear_regression", function=train_linear_regression, input=train_data_cfg, output=model_cfg) task_forecast_cfg = Config.configure_task(id="task_forecast_linear_regression", function=forecast_linear_regression, input=[model_cfg, date_cfg], output=predictions_cfg) pipeline_linear_regression_cfg = Config.configure_pipeline(id="LinearRegression", task_configs=[task_train_cfg, task_forecast_cfg, task_result_cfg]) scenario_cfg = Config.configure_scenario(id='scenario', pipeline_configs=[pipeline_preprocessing_cfg, pipeline_arima_cfg, pipeline_linear_regression_cfg])
|
import pandas as pd from pmdarima import auto_arima from sklearn.linear_model import LinearRegression import datetime as dt import numpy as np def add_features(data): dates = pd.to_datetime(data["Date"]) data["Months"] = dates.dt.month data["Days"] = dates.dt.isocalendar().day data["Week"] = dates.dt.isocalendar().week data["Day of week"] = dates.dt.dayofweek return data def create_train_data(final_data, date): bool_index = pd.to_datetime(final_data['Date']) <= date train_data = final_data[bool_index] return train_data def preprocess(initial_data, country, date): data = initial_data.groupby(["Country/Region",'Date'])\ .sum()\ .dropna()\ .reset_index() final_data = data.loc[data['Country/Region']==country].reset_index(drop=True) final_data = final_data[['Date','Deaths']] final_data = add_features(final_data) train_data = create_train_data(final_data, date) return final_data, train_data def train_arima(train_data): model = auto_arima(train_data['Deaths'], start_p=1, start_q=1, max_p=5, max_q=5, start_P=0, seasonal=False, d=1, D=1, trace=True, error_action='ignore', suppress_warnings=True) model.fit(train_data['Deaths']) return model def forecast(model): predictions = model.predict(n_periods=60) return np.array(predictions) def result(final_data, predictions, date): dates = pd.to_datetime([date + dt.timedelta(days=i) for i in range(len(predictions))]) final_data['Date'] = pd.to_datetime(final_data['Date']) predictions = pd.concat([pd.Series(dates, name="Date"), pd.Series(predictions, name="Predictions")], axis=1) return final_data.merge(predictions, on="Date", how="outer") def train_linear_regression(train_data): y = train_data['Deaths'] X = train_data.drop(['Deaths','Date'], axis=1) model = LinearRegression() model.fit(X,y) return model def forecast_linear_regression(model, date): dates = pd.to_datetime([date + dt.timedelta(days=i) for i in range(60)]) X = add_features(pd.DataFrame({"Date":dates})) X.drop('Date', axis=1, inplace=True) predictions = model.predict(X) return predictions
|
import pandas as pd path_to_data = "data/covid-19-all.csv" data = pd.read_csv(path_to_data, low_memory=False)
|
from taipy.gui import Markdown import numpy as np import json from data.data import data type_selector = ['Absolute', 'Relative'] selected_type = type_selector[0] def initialize_world(data): data_world = data.groupby(["Country/Region", 'Date'])\ .sum()\ .reset_index() with open("data/pop.json","r") as f: pop = json.load(f) data_world['Population'] = [0]*len(data_world) for i in range(len(data_world)): data_world['Population'][i] = pop[data_world.loc[i, "Country/Region"]][1] data_world = data_world.dropna()\ .reset_index() data_world['Deaths/100k'] = data_world.loc[:,'Deaths']/data_world.loc[:,'Population']*100000 data_world_pie_absolute = data_world.groupby(["Country/Region"])\ .max()\ .sort_values(by='Deaths', ascending=False)[:20]\ .reset_index() data_world_pie_relative = data_world.groupby(["Country/Region"])\ .max()\ .sort_values(by='Deaths/100k', ascending=False)[:20]\ .reset_index()\ .drop(columns=['Deaths']) country_absolute = data_world_pie_absolute['Country/Region'].unique().tolist() country_relative = data_world_pie_relative.loc[:,'Country/Region'].unique().tolist() data_world_evolution_absolute = data_world[data_world['Country/Region'].str.contains('|'.join(country_absolute),regex=True)] data_world_evolution_absolute = data_world_evolution_absolute.pivot(index='Date', columns='Country/Region', values='Deaths')\ .reset_index() data_world_evolution_relative = data_world[data_world['Country/Region'].str.contains('|'.join(country_relative),regex=True)] data_world_evolution_relative = data_world_evolution_relative.pivot(index='Date', columns='Country/Region', values='Deaths/100k')\ .reset_index() return data_world, data_world_pie_absolute, data_world_pie_relative, data_world_evolution_absolute, data_world_evolution_relative data_world,\ data_world_pie_absolute, data_world_pie_relative,\ data_world_evolution_absolute, data_world_evolution_relative = initialize_world(data) data_world_evolution_absolute_properties = {"x":"Date"} cols = [col for col in data_world_evolution_absolute.columns if col != "Date"] for i in range(len(cols)): data_world_evolution_absolute_properties[f'y[{i}]'] = cols[i] data_world_evolution_relative_properties = {"x":"Date"} cols = [col for col in data_world_evolution_relative.columns if col != "Date"] for i in range(len(cols)): data_world_evolution_relative_properties[f'y[{i}]'] = cols[i] world_md = Markdown(""" # **World**{: .color-primary} Statistics <|{selected_type}|toggle|lov={type_selector}|> <|layout|columns=1 1 1 1|gap=30px| <|card m1| #### **Deaths**{: .color-primary} <br/> # <|{'{:,}'.format(int(np.sum(data_world_pie_absolute['Deaths']))).replace(',', ' ')}|text|raw|> |> <|card m1| #### **Recovered**{: .color-primary} <br/> # <|{'{:,}'.format(int(np.sum(data_world_pie_absolute['Recovered']))).replace(',', ' ')}|text|raw|> |> <|card m1| #### **Confirmed**{: .color-primary} <br/> # <|{'{:,}'.format(int(np.sum(data_world_pie_absolute['Confirmed']))).replace(',', ' ')}|text|raw|> |> |> <br/> <|part|render={selected_type=='Absolute'}| <|layout|columns=1 2|gap=30px| <|{data_world_pie_absolute}|chart|type=pie|label=Country/Region|x=Deaths|> <|{data_world_evolution_absolute}|chart|properties={data_world_evolution_absolute_properties}|> |> |> <|part|render={selected_type=='Relative'}| <|layout|columns=1 2|gap=30px| <|{data_world_pie_relative}|chart|type=pie|label=Country/Region|x=Deaths/100k|> <|{data_world_evolution_relative}|chart|properties={data_world_evolution_relative_properties}|> |> |> """)
|
from taipy.gui import Markdown, invoke_long_callback import taipy as tp import pandas as pd import datetime as dt from config.config import scenario_cfg scenario_selector = [(s.id, s.name) for s in tp.get_scenarios()] selected_scenario = None selected_date = dt.datetime(2020,10,1) scenario_country = "No selected scenario" scenario_date = "No selected scenario" scenario_name = "" result = pd.DataFrame({"Date":[dt.datetime(2020,1,1)], "Deaths_x":[0],"Deaths_y":[0], "Predictions_x":[0],"Predictions_y":[0]}) def create_new_scenario(state): if state.scenario_name is not None or state.scenario_name == "": scenario = tp.create_scenario(scenario_cfg, name=state.scenario_name) state.scenario_selector += [(scenario.id, scenario.name)] state.selected_scenario = scenario.id actualize_graph(state) def submit_heavy(scenario): tp.submit(scenario) def submit_status(state, status): actualize_graph(state) def submit_scenario(state): # 1) get the selected scenario # 2) write in country Data Node, the selected country # 3) submit the scenario # 4) actualize le graph avec actualize_graph if state.selected_scenario is not None: scenario = tp.get(state.selected_scenario) scenario.country.write(state.selected_country) scenario.date.write(state.selected_date.replace(tzinfo=None)) invoke_long_callback(state, submit_heavy, [scenario], submit_status) def actualize_graph(state): # 1) update the result dataframe # 2) change selected_country with the predicted country of the scenario if state.selected_scenario is not None: scenario = tp.get(state.selected_scenario) result_arima = scenario.pipelines['ARIMA'].result.read() result_rd = scenario.pipelines['LinearRegression'].result.read() if result_arima is not None and result_rd is not None: state.result = result_rd.merge(result_arima, on="Date", how="outer").sort_values(by='Date') else: state.result = result state.scenario_country = scenario.country.read() state.scenario_date = scenario.date.read().strftime("%d %B %Y") predictions_md = Markdown(""" # **Prediction**{: .color-primary} page ## Scenario Creation <|layout|columns=5 5 5 5|gap=30px| **Scenario Name** <br/> <|{scenario_name}|input|label=Name|> <br/> <|Create|button|on_action=create_new_scenario|> **Prediction Date** <br/> <|{selected_date}|date|label=Prediction date|> <|Submit|button|on_action=submit_scenario|> **Country** <br/> <|{selected_country}|selector|lov={selector_country}|dropdown|on_change=on_change_country|label=Country|> |> --------------------------------------- ## Result <|layout|columns=2 3 3|gap=30px| <|{selected_scenario}|selector|lov={scenario_selector}|on_change=actualize_graph|dropdown|value_by_id|label=Scenario|> <|card m1| #### Country of prediction : <|{scenario_country}|> |> <|card m1| #### Date of prediction : <|{scenario_date}|> |> |> <br/> <|{result}|chart|x=Date|y[1]=Deaths_x|type[1]=bar|y[2]=Predictions_x|y[3]=Predictions_y|> """)
|
import numpy as np from taipy.gui import Markdown from data.data import data marker_map = {"color":"Deaths", "size": "Size", "showscale":True, "colorscale":"Viridis"} layout_map = { "dragmode": "zoom", "mapbox": { "style": "open-street-map", "center": { "lat": 38, "lon": -90 }, "zoom": 3} } options = {"unselected":{"marker":{"opacity":0.5}}} def initialize_map(data): data['Province/State'] = data['Province/State'].fillna(data["Country/Region"]) data_province = data.groupby(["Country/Region", 'Province/State', 'Longitude', 'Latitude'])\ .max() data_province_displayed = data_province[data_province['Deaths']>10].reset_index() data_province_displayed['Size'] = np.sqrt(data_province_displayed.loc[:,'Deaths']/data_province_displayed.loc[:,'Deaths'].max())*80 + 3 data_province_displayed['Text'] = data_province_displayed.loc[:,'Deaths'].astype(str) + ' deaths </br> ' + data_province_displayed.loc[:,'Province/State'] return data_province_displayed data_province_displayed = initialize_map(data) map_md = Markdown(""" # **Map**{: .color-primary} Statistics <|{data_province_displayed}|chart|type=scattermapbox|lat=Latitude|lon=Longitude|marker={marker_map}|layout={layout_map}|text=Text|mode=markers|height=800px|options={options}|> """)
|
import numpy as np import pandas as pd from taipy.gui import Markdown from data.data import data selected_country = 'France' data_country_date = None representation_selector = ['Cumulative', 'Density'] selected_representation = representation_selector[0] layout = {'barmode':'stack', "hovermode":"x"} options = {"unselected":{"marker":{"opacity":0.5}}} country_md = "<|{data_country_date}|chart|type=bar|x=Date|y[1]=Deaths|y[2]=Recovered|y[3]=Confirmed|layout={layout}|options={options}|>" def initialize_case_evolution(data, selected_country='France'): # Aggregation of the dataframe to erase the regions that will not be used here data_country_date = data.groupby(["Country/Region",'Date'])\ .sum()\ .reset_index() # a country is selected, here France by default data_country_date = data_country_date.loc[data_country_date['Country/Region']==selected_country] return data_country_date data_country_date = initialize_case_evolution(data) pie_chart = pd.DataFrame({"labels": ["Deaths", "Recovered", "Confirmed"],"values": [data_country_date.iloc[-1, 6], data_country_date.iloc[-1, 5], data_country_date.iloc[-1, 4]]}) def convert_density(state): if state.selected_representation == 'Density': df_temp = state.data_country_date.copy() df_temp['Deaths'] = df_temp['Deaths'].diff().fillna(0) df_temp['Recovered'] = df_temp['Recovered'].diff().fillna(0) df_temp['Confirmed'] = df_temp['Confirmed'].diff().fillna(0) state.data_country_date = df_temp else: state.data_country_date = initialize_case_evolution(data, state.selected_country) def on_change_country(state): # state contains all the Gui variables and this is through this state variable that we can update the Gui # state.selected_country, state.data_country_date, ... # update data_country_date with the right country (use initialize_case_evolution) print("Chosen country: ", state.selected_country) state.data_country_date = initialize_case_evolution(data, state.selected_country) state.pie_chart = pd.DataFrame({"labels": ["Deaths", "Recovered", "Confirmed"], "values": [state.data_country_date.iloc[-1, 6], state.data_country_date.iloc[-1, 5], state.data_country_date.iloc[-1, 4]]}) if state.selected_representation == 'Density': convert_density(state) country_md = Markdown("pages/country.md")
|
from taipy.gui import Gui, notify text = "" revealed = False page = """ <|{text if text else 'Write something in the input'}|> <|{text}|input|on_change={lambda state: notify(state, 'i', s.text)}|> <|part|render={len(text)>0}| Part hidden and discovered after input |> ----- <|Push|button|on_action={lambda state: state.assign("revealed", True)}|> <|part|render={revealed}| Part hidden and discovered after button |> """ Gui(page).run()
|
# Write an app that calls a function every 5 seconds
|
from taipy.gui import Gui, Markdown, invoke_long_callback, notify import numpy as np status = 0 num_iterations = 10_000_000 pi_list = [] def pi_approx(num_iterations): k, s = 3.0, 1.0 pi_list = [] for i in range(num_iterations): s = s-((1/k) * (-1)**i) k += 2 if (i+1)%(int(num_iterations/1_000)+1) == 0: pi_list += [np.abs(4*s-np.pi)] return pi_list def heavy_status(state, status, pi_list): notify(state, 'i', f"Status parameter: {status}") if isinstance(status, bool): if status: notify(state, 'success', "Finished") state.pi_list = pi_list else: notify(state, 'error', f"An error was raised") else: state.status += 1 def on_action(state): invoke_long_callback(state, pi_approx, [int(state.num_iterations)], heavy_status, [], 2000) page = Markdown(""" How many times was the status function called? <|{status}|> ## Number of approximation <|{num_iterations}|number|label=# of approximation|> <|Approximate pie|button|on_action=on_action|> ## Evolution of approximation <|{pi_list}|chart|layout={layout}|> """) layout = { "yaxis": { "type": 'log', "autorange": True } } Gui(page).run()
|
from taipy.gui import Gui, notify text = "" page_1 = """ # Page 1 <|{text}|> """ page_2 = """ # Page 2 <|Raise error|button|on_action=raise_error|> """ hidden_page_3 = """ # Hidden Page """ def raise_error(state): raise(ValueError("This is an error")) def on_init(state): print("When a new client connects, this function is called") state.text = "Hello, world!" def on_change(state, var_name, var_value): notify(state, 'i', f'{var_name} changed') def on_navigate(state, page_name: str): if page_name == "hidden_page_3": return "page_1" notify(state, 'i', f'{page_name} navigated') return page_name def on_exception(state, function_name: str, ex: Exception): err = f"A problem occured in {function_name}" print(err) notify(state, 'e', err) pages = { "/":"<|navbar|>", "page_1": page_1, "page_2": page_2, "hidden_page_3": hidden_page_3} Gui(pages=pages).run(port=5003)
|
from taipy.gui import Gui selected = [] a = [1, 2] b = [2, 3] selector_lov = [a, b] page = """ <|{selected}|selector|lov={selector_lov}|adapter={lambda s: s.name}|> """ gui = Gui(page) gui.run()
|
from taipy.gui import Gui from math import cos, exp value = 10 page = """ Markdown # Taipy *Demo* Value: <|{value}|text|> <|{value}|slider|on_change=on_slider|> <|{data}|chart|> """ def on_slider(state): state.data = compute_data(state.value) def compute_data(decay:int)->list: return [cos(i/6) * exp(-i*decay/600) for i in range(100)] data = compute_data(value) Gui(page).run(use_reloader=True, port=5002)
|
from taipy.gui import Gui from math import cos, exp value = 10 page = """ Markdown # Taipy *Demo* """ Gui(page).run(use_reloader=True, port=5002)
|
# Write an app that create simple charts by poviding inputs and diplay them
|
from taipy.gui import Gui title = 1 md = """ <|{title}|number|on_change=change_partial|> <|part|partial={p}|> """ def change_partial(state): title_int = int(state.title) new_html = f'<h{title_int}>test{title_int}</h{title_int}>' print(new_html) state.p.update_content(state, new_html) gui = Gui(md) p = gui.add_partial("<h1>test</h1>") gui.run(port=5001)
|
import yfinance as yf from taipy.gui import Gui from taipy.gui.data.decimator import MinMaxDecimator, RDP, LTTB df_AAPL = yf.Ticker("AAPL").history(interval="1d", period = "100Y") df_AAPL["DATE"] = df_AAPL.index.astype(int).astype(float) n_out = 500 decimator_instance = MinMaxDecimator(n_out=n_out) decimate_data_count = len(df_AAPL) page = """ # Decimator From a data length of <|{len(df_AAPL)}|> to <|{n_out}|> ## Without decimator <|{df_AAPL}|chart|x=DATE|y=Open|> ## With decimator <|{df_AAPL}|chart|x=DATE|y=Open|decimator=decimator_instance|> """ gui = Gui(page) gui.run(port=5025)
|
from taipy import Config import taipy as tp def read_text(path: str) -> str: with open(path, 'r') as text_reader: data = text_reader.read() return data def write_text(data: str, path: str) -> None: with open(path, 'w') as text_writer: text_writer.write(data) historical_data_cfg = Config.configure_generic_data_node( id="historical_data", read_fct=read_text, write_fct=write_text, read_fct_args=["../data.txt"], write_fct_args=["../data.txt"]) scenario_cfg = Config.configure_scenario(id="my_scenario", additional_data_node_configs=[historical_data_cfg]) scenario = tp.create_scenario(scenario_cfg)
|
import taipy as tp from config.config_toml import scenario_cfg if __name__=="__main__": tp.Core().run() scenario_1 = tp.create_scenario(scenario_cfg) scenario_2 = tp.create_scenario(scenario_cfg) scenario_1.submit() scenario_2.submit() scenario_1 = tp.create_scenario(scenario_cfg) scenario_1.submit(wait=True) scenario_1.submit(wait=True, timeout=5)
|
import taipy as tp from config.config import scenario_cfg if __name__=="__main__": tp.Core().run() scenario_1 = tp.create_scenario(scenario_cfg) scenario_2 = tp.create_scenario(scenario_cfg) scenario_1.submit() scenario_2.submit() scenario_1 = tp.create_scenario(scenario_cfg) scenario_1.submit(wait=True) scenario_1.submit(wait=True, timeout=5)
|
from taipy import Config from algos.algos import * Config.configure_job_executions(mode="standalone", max_nb_of_workers=2) # Configuration of Data Nodes input_cfg = Config.configure_data_node("input", default_data=21) intermediate_cfg = Config.configure_data_node("intermediate", default_data=21) output_cfg = Config.configure_data_node("output") # Configuration of tasks first_task_cfg = Config.configure_task("double", double, input_cfg, intermediate_cfg) second_task_cfg = Config.configure_task("add", add, intermediate_cfg, output_cfg) # Configuration of the pipeline and scenario scenario_cfg = Config.configure_scenario(id="my_scenario", task_configs=[first_task_cfg, second_task_cfg]) Config.export("config_07.toml")
|
from taipy import Config from algos.algos import * Config.load('config/config_07.toml') Config.configure_job_executions(mode="standalone", max_nb_of_workers=2) scenario_cfg = Config.scenarios['my_scenario']
|
import time # Normal function used by Taipy def double(nb): return nb * 2 def add(nb): print("Wait 5 seconds in add function") time.sleep(5) return nb + 10
|
import taipy as tp from taipy.gui import Markdown from config.config import * scenario = None df_metrics = None data_node = None pages = {'/':'<|navbar|> <|toggle|theme|> <br/>', 'Scenario': Markdown('pages/scenario.md'), 'Data-Node': Markdown('pages/data_node.md')} if __name__ == "__main__": tp.Core().run() tp.Gui(pages=pages).run(port=4999)
|
import taipy as tp import datetime as dt from config.config import * def create_and_run_scenario(date: dt.datetime): scenario = tp.create_scenario(config=scenario_cfg, name=f"scenario_{date.date()}", creation_date=date) scenario.day.write(date) tp.submit(scenario) return scenario if __name__ == "__main__": tp.Core().run() my_first_scenario = create_and_run_scenario(dt.datetime(2021, 1, 25)) predictions = my_first_scenario.predictions.read() print("Predictions\n", predictions) [s for s in tp.get_scenarios()] [d for d in tp.get_data_nodes()]
|
from taipy import Config, Scope, Frequency from taipy.core import Scenario import datetime as dt from algos.algos import clean_data, predict, evaluate ## Input Data Nodes initial_dataset_cfg = Config.configure_data_node(id="initial_dataset", storage_type="csv", path="data/dataset.csv", scope=Scope.GLOBAL) # We assume the current day is the 26th of July 2021. # This day can be changed to simulate multiple executions of scenarios on different days day_cfg = Config.configure_data_node(id="day", default_data=dt.datetime(2021, 7, 26)) ## Remaining Data Node cleaned_dataset_cfg = Config.configure_data_node(id="cleaned_dataset", storage_type="parquet", scope=Scope.GLOBAL) predictions_cfg = Config.configure_data_node(id="predictions") # Task config objects clean_data_task_cfg = Config.configure_task(id="clean_data", function=clean_data, input=initial_dataset_cfg, output=cleaned_dataset_cfg, skippable=True) predict_task_cfg = Config.configure_task(id="predict", function=predict, input=[cleaned_dataset_cfg, day_cfg], output=predictions_cfg) evaluation_cfg = Config.configure_data_node(id="evaluation") evaluate_task_cfg = Config.configure_task(id="evaluate", function=evaluate, input=[predictions_cfg, cleaned_dataset_cfg, day_cfg], output=evaluation_cfg) # # Configure our scenario config. scenario_cfg = Config.configure_scenario(id="scenario", task_configs=[clean_data_task_cfg, predict_task_cfg,evaluate_task_cfg], frequency=Frequency.MONTHLY) Config.export('config/config.toml')
|
import datetime as dt import pandas as pd def clean_data(initial_dataset: pd.DataFrame): print(" Cleaning data") initial_dataset['Date'] = pd.to_datetime(initial_dataset['Date']) cleaned_dataset = initial_dataset[['Date', 'Value']] return cleaned_dataset def predict(cleaned_dataset: pd.DataFrame, day: dt.datetime): print(" Predicting") train_dataset = cleaned_dataset[cleaned_dataset['Date'] < pd.Timestamp(day.date())] predictions = train_dataset['Value'][-30:].reset_index(drop=True) return pd.DataFrame({"Prediction":predictions}) def evaluate(predictions, cleaned_dataset, day): print(" Evaluating") expected = cleaned_dataset.loc[cleaned_dataset['Date'] >= pd.Timestamp(day.date()), 'Value'][:30].reset_index(drop=True) mae = ((predictions['Prediction'] - expected) ** 2).mean() return int(mae)
|
from taipy.gui import Gui, notify import datetime as dt import yfinance as yf def get_stock_data(ticker): now = dt.date.today() past = now - dt.timedelta(days=365*2) return yf.download(ticker, past, now).reset_index() def update_ticker(state): # state.data = ... ticker = 'AAPL' data = get_stock_data(ticker) historical = """ """ Gui(historical).run()
|
from taipy.gui import Gui, notify import datetime as dt import yfinance as yf def get_stock_data(ticker): now = dt.date.today() past = now - dt.timedelta(days=365*2) return yf.download(ticker, past, now).reset_index() def update_ticker(state): state.data = get_stock_data(state.ticker) notify(state, "success", "Ticker updated!") ticker = 'AAPL' data = get_stock_data(ticker) historical = """ #### Stock Price **Analysis**{: .color-primary} <|{ticker}|toggle|lov=MSFT;GOOG;AAPL|on_change=update_ticker|> Mean Volume: <|{int(data['Volume'].mean())}|> <|{data}|chart|x=Date|y=Volume|> """ Gui(historical).run()
|
from taipy.gui import Gui import taipy as tp from pages.data_viz import historical from pages.predictions_sol import predictions, scenario ticker = 'AAPL' pages = {"/":"<|navbar|>", "Historical":historical, "Prediction":predictions} tp.Core().run() Gui(pages=pages).run(port=5001)
|
from datetime import timedelta import yfinance as yf from prophet import Prophet def get_data(ticker, date): past = date - timedelta(days=365*7) return yf.download(ticker, past, date).reset_index() def predict(preprocessed_dataset): df_train = preprocessed_dataset[['Date', 'Close']] df_train = df_train.rename(columns={"Date": "ds", "Close": "y"}) # This is the format that Prophet accepts m = Prophet() m.fit(df_train) future = m.make_future_dataframe(periods=365) predictions = m.predict(future)[['ds', 'yhat']].rename(columns={'ds': 'Date', 'yhat': 'Predictions'})[-365:] return predictions.reset_index()
|
import taipy as tp from taipy.gui import notify, Markdown import datetime as dt tp.Config.load("config/config.toml") ticker = 'AAPL' scenario = None data_node = None jobs = [] default_data = {"Date":[0], "Predictions":[0]} def on_submission_status_change(state, submittable, details): submission_status = details.get('submission_status') if submission_status == 'COMPLETED': print(f"{submittable.name} has completed.") notify(state, 'success', 'Completed!') state.refresh('scenario') elif submission_status == 'FAILED': print(f"{submittable.name} has failed.") notify(state, 'error', 'Completed!') predictions = Markdown(""" Put a scenario selector ### **Daily**{: .color-primary} Predictions <|{scenario.ticker.read() if scenario else ticker}|toggle|lov=MSFT;GOOG;AAPL|active={scenario}|on_change=save|> Put a scenario viewer <|{show_preditions(scenario)}|chart|x=Date|y=Predictions|> <|1 5|layout| Put a Data Node selector Put a Data Node |> Put a job selector """) def show_preditions(scenario): if scenario and scenario.predictions.read() is not None: print(scenario) return scenario.predictions.read() else: return default_data def save(state, var_name, var_value): state.scenario.ticker.write(var_value) state.scenario.date.write(dt.date.today()) notify(state, "success", 'Parameters saved: ready for submission!') state.scenario.predictions.write(None) state.scenario = state.scenario
|
import taipy as tp from taipy.gui import notify, Markdown import datetime as dt tp.Config.load("config/config.toml") ticker = 'AAPL' scenario = None data_node = None jobs = [] default_data = {"Date":[0], "Predictions":[0]} def on_submission_status_change(state, submittable, details): submission_status = details.get('submission_status') if submission_status == 'COMPLETED': print(f"{submittable.name} has completed.") notify(state, 'success', 'Completed!') state.refresh('scenario') elif submission_status == 'FAILED': print(f"{submittable.name} has failed.") notify(state, 'error', 'Completed!') predictions = Markdown(""" <|{scenario}|scenario_selector|> ### **Daily**{: .color-primary} Predictions <|{scenario.ticker.read() if scenario else ticker}|toggle|lov=MSFT;GOOG;AAPL|active={scenario}|on_change=save|> <|{scenario}|scenario|on_submission_change=on_submission_status_change|> <|{show_preditions(scenario)}|chart|x=Date|y=Predictions|> <|1 5|layout| <|{data_node}|data_node_selector|> <|{data_node}|data_node|> |> <|{jobs}|job_selector|> """) def show_preditions(scenario): if scenario and scenario.predictions.read() is not None: print(scenario) return scenario.predictions.read() else: return default_data def save(state, var_name, var_value): state.scenario.ticker.write(var_value) state.scenario.date.write(dt.date.today()) notify(state, "success", 'Parameters saved: ready for submission!') state.scenario.predictions.write(None) state.scenario = state.scenario
|
from taipy.gui import notify, Markdown import datetime as dt import yfinance as yf def get_stock_data(ticker): now = dt.date.today() past = now - dt.timedelta(days=365*2) return yf.download(ticker, past, now).reset_index() def update_ticker(state): state.data = get_stock_data(state.ticker) notify(state, "success", "Ticker updated!") ticker = 'AAPL' data = get_stock_data(ticker) historical = Markdown(""" ## Stock Price **Analysis**{: .color-primary} <|{ticker}|toggle|lov=MSFT;GOOG;AAPL|on_change=update_ticker|> <|{data}|chart|x=Date|y=Volume|> """)
|
from taipy import Gui import pandas as pd import requests API_URL = "https://api-inference.huggingface.co/models/bigcode/starcoder" headers = {"Authorization": "Bearer [ENTER-YOUR-API-KEY-HERE]"} DATA_PATH = "data.csv" df = pd.read_csv(DATA_PATH, sep=";") data = pd.DataFrame( { "Date": pd.to_datetime( [ "2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04", "2020-01-05", "2020-01-06", "2020-01-07", ] ), "Sales": [100, 250, 500, 400, 450, 600, 650], "Revenue": [150, 200, 600, 800, 850, 900, 950], "Energy": ["Oil", "Coal", "Gas", "Nuclear", "Hydro", "Solar", "Wind"], "Usage": [0.33, 0.27, 0.21, 0.06, 0.05, 0.05, 0.03], } ) context = "" for instruction, code in zip(df["instruction"], df["code"]): context += f"{instruction}\n{code}\n" def query(payload: dict) -> dict: """ Queries StarCoder API Args: payload: Payload for StarCoder API Returns: dict: StarCoder API response """ response = requests.post(API_URL, headers=headers, json=payload, timeout=20) return response.json() def prompt(input_instruction: str) -> str: """ Prompts StarCoder to generate Taipy GUI code Args: instuction (str): Instruction for StarCoder Returns: str: Taipy GUI code """ current_prompt = f"{context}\n{input_instruction}\n" output = "" final_result = "" # Re-query until the output contains the closing tag timeout = 0 while ">" not in output and timeout < 10: output = query( { "inputs": current_prompt + output, "parameters": { "return_full_text": False, }, } )[0]["generated_text"] timeout += 1 final_result += output output_code = f"""<{final_result.split("<")[1].split(">")[0]}>""" return output_code def on_enter_press(state) -> None: """ Prompt StarCoder to generate Taipy GUI code when user presses enter Args: state (State): Taipy GUI state """ state.result = prompt(state.instruction) state.p.update_content(state, state.result) print(state.result) instruction = "" result = "" page = """ # Taipy**Copilot**{: .color-primary} Enter your instruction here: <|{instruction}|input|on_action=on_enter_press|class_name=fullwidth|> <|Data|expandable| <|{data[:5]}|table|width=100%|show_all=True|> |> <|part|partial={p}|> """ gui = Gui(page) p = gui.add_partial("""<|{data}|chart|mode=lines|x=Date|y=Sales|>""") gui.run()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.