thanhnew2001 commited on
Commit
732aafb
·
1 Parent(s): 43c3ae3

Create data.jsonl

Browse files
Files changed (1) hide show
  1. data.jsonl +10 -0
data.jsonl ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {"text": "# Create app to read and display data from Excel file import pandas as pd from taipy import Gui # ---- READ EXCEL ---- df = pd.read_excel( io=\"data/supermarkt_sales.xlsx\", engine=\"openpyxl\", sheet_name=\"Sales\", skiprows=3, usecols=\"B:R\", nrows=1000, ) # Add 'hour' column to dataframe df[\"hour\"] = pd.to_datetime(df[\"Time\"], format=\"%H:%M:%S\").dt.hour # initialization of variables cities = list(df[\"City\"].unique()) types = list(df[\"Customer_type\"].unique()) genders = list(df[\"Gender\"].unique()) city = cities customer_type = types gender = genders layout = {\"margin\": {\"l\": 220}} # Markdown for the entire page ## NOTE: {: .orange} references a color from main.css use to style my text ## <text| ## |text> ## \"text\" here is just a name given to my part/my section ## it has no meaning in the code page = \"\"\"<|toggle|theme|> <|layout|columns=20 80|gap=30px| <sidebar| ## Please **filter**{: .orange} here: <|{city}|selector|lov={cities}|multiple|label=Select the City|dropdown|on_change=on_filter|width=100%|> <|{customer_type}|selector|lov={types}|multiple|label=Select the Customer Type|dropdown|on_change=on_filter|width=100%|> <|{gender}|selector|lov={genders}|multiple|label=Select the Gender|dropdown|on_change=on_filter|width=100%|> |sidebar> <main_page| # \ud83d\udcca **Sales**{: .orange} Dashboard <|layout|columns=1 1 1| <total_sales| ## **Total**{: .orange} sales: ### US $ <|{int(df_selection[\"Total\"].sum())}|> |total_sales> <average_rating| ## **Average**{: .orange} Rating: ### <|{round(df_selection[\"Rating\"].mean(), 1)}|> <|{\"\u2b50\" * int(round(round(df_selection[\"Rating\"].mean(), 1), 0))}|> |average_rating> <average_sale| ## Average Sales Per **Transaction**{: .orange}: ### US $ <|{round(df_selection[\"Total\"].mean(), 2)}|> |average_sale> |> <br/> Display df_selection in an expandable <|Sales Table|expandable|expanded=False| <|{df_selection}|table|width=100%|page_size=5|rebuild|class_name=table|> |> <charts| <|{sales_by_hour}|chart|x=Hour|y=Total|type=bar|title=Sales by Hour|color=#ff462b|> <|{sales_by_product_line}|chart|x=Total|y=Product|type=bar|orientation=h|title=Sales by Product|layout={layout}|color=#ff462b|> |charts> |main_page> |> Code from [Coding is Fun](https://github.com/Sven-Bo) Get the Taipy Code [here](https://github.com/Avaiga/demo-sales-dashboard) and the original code [here](https://github.com/Sven-Bo/streamlit-sales-dashboard) \"\"\" def filter(city, customer_type, gender): df_selection = df[ df[\"City\"].isin(city) & df[\"Customer_type\"].isin(customer_type) & df[\"Gender\"].isin(gender) ] # SALES BY PRODUCT LINE [BAR CHART] sales_by_product_line = ( df_selection[[\"Product line\", \"Total\"]] .groupby(by=[\"Product line\"]) .sum()[[\"Total\"]] .sort_values(by=\"Total\") ) sales_by_product_line[\"Product\"] = sales_by_product_line.index # SALES BY HOUR [BAR CHART] sales_by_hour = ( df_selection[[\"hour\", \"Total\"]].groupby(by=[\"hour\"]).sum()[[\"Total\"]] ) sales_by_hour[\"Hour\"] = sales_by_hour.index return df_selection, sales_by_product_line, sales_by_hour def on_filter(state): state.df_selection, state.sales_by_product_line, state.sales_by_hour = filter( state.city, state.customer_type, state.gender ) if __name__ == \"__main__\": # initialize dataframes df_selection, sales_by_product_line, sales_by_hour = filter( city, customer_type, gender ) # run the app Gui(page).run() "}
2
+ {"text": "# Create an app with slider and chart 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 compute_data(decay:int)->list: return [cos(i/6) * exp(-i*decay/600) for i in range(100)] def on_slider(state): state.data = compute_data(state.value) data = compute_data(value) Gui(page).run(use_reloader=True, port=5002)"}
3
+ {"text": "# Create app to predict covid in the world from taipy.gui import Gui import taipy as tp from pages.country.country import country_md from pages.world.world import world_md from pages.map.map import map_md from pages.predictions.predictions import predictions_md, selected_scenario from pages.root import root, selected_country, selector_country from config.config import Config pages = { '/':root, \"Country\":country_md, \"World\":world_md, \"Map\":map_md, \"Predictions\":predictions_md } gui_multi_pages = Gui(pages=pages) if __name__ == '__main__': tp.Core().run() gui_multi_pages.run(title=\"Covid Dashboard\") "}
4
+ {"text": "# Create app for finance data analysis 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(\"int64\").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=5026) "}
5
+ {"text": "# Create an app to upload a csv and display it in a table from taipy.gui import Gui import pandas as pd data = [] data_path = \"\" def data_upload(state): state.data = pd.read_csv(state.data_path) page = \"\"\" <|{data_path}|file_selector|on_action=data_upload|> <|{data}|table|> \"\"\" Gui(page).run() "}
6
+ {"text": "# Create an app to visualize sin and amp with slider and chart from taipy.gui import Gui from math import cos, exp state = {\"amp\": 1, \"data\":[]} def update(state): x = [i/10 for i in range(100)] y = [math.sin(i)*state.amp for i in x] state.data = [{\"data\": y}] page = \"\"\" Amplitude: <|{amp}|slider|> <|Data|chart|data={data}|> \"\"\" Gui(page).run(state=state)"}
7
+ {"text": "# Create an app to visualize sin, cos with slider and chart from taipy.gui import Gui from math import sin, cos, pi state = { \"frequency\": 1, \"decay\": 0.01, \"data\": [] } page = \"\"\" # Sine and Cosine Functions Frequency: <|{frequency}|slider|min=0|max=10|step=0.1|on_change=update|> Decay: <|{decay}|slider|min=0|max=1|step=0.01|on_change=update|> <|Data|chart|data={data}|> \"\"\" def update(state): x = [i/10 for i in range(100)] y1 = [sin(i*state.frequency*2*pi) * exp(-i*state.decay) for i in x] y2 = [cos(i*state.frequency*2*pi) * exp(-i*state.decay) for i in x] state.data = [ {\"name\": \"Sine\", \"data\": y1}, {\"name\": \"Cosine\", \"data\": y2} ] Gui(page).run(use_reloader=True, state=state)"}
8
+ {"text": "# Create app to visualize country population 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}}} 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]]}) convert_density(state) page =\"\"\" # **Country**{: .color-primary} Statistics <|layout|columns=1 1 1| <|{selected_country}|selector|lov={selector_country}|on_change=on_change_country|dropdown|label=Country|> <|{selected_representation}|toggle|lov={representation_selector}|on_change=convert_density|> |> <br/> <|layout|columns=1 1 1 1|gap=50px| <|card| **Deaths**{: .color-primary} <|{'{:,}'.format(int(data_country_date.iloc[-1]['Deaths'])).replace(',', ' ')}|text|class_name=h2|> |> <|card| **Recovered**{: .color-primary} <|{'{:,}'.format(int(data_country_date.iloc[-1]['Recovered'])).replace(',', ' ')}|text|class_name=h2|> |> <|card| **Confirmed**{: .color-primary} <|{'{:,}'.format(int(data_country_date.iloc[-1]['Confirmed'])).replace(',', ' ')}|text|class_name=h2|> |> |> <br/> <|layout|columns=2 1| <|{data_country_date}|chart|type=bar|x=Date|y[3]=Deaths|y[2]=Recovered|y[1]=Confirmed|layout={layout}|options={options}|title=Covid Evolution|> <|{pie_chart}|chart|type=pie|values=values|labels=labels|title=Distribution between cases|> |> \"\"\" Gui(page).run(use_reloader=True, state=state)"}
9
+ {"text": "# Create Taipy app to generate mandelbrot fractals from taipy import Gui import numpy as np from PIL import Image import matplotlib.pyplot as plt WINDOW_SIZE = 500 cm = plt.cm.get_cmap(\"viridis\") def generate_mandelbrot( center: int = WINDOW_SIZE / 2, dx_range: int = 1000, dx_start: float = -0.12, dy_range: float = 1000, dy_start: float = -0.82, iterations: int = 50, max_value: int = 200, i: int = 0, ) -> str: mat = np.zeros((WINDOW_SIZE, WINDOW_SIZE)) for y in range(WINDOW_SIZE): for x in range(WINDOW_SIZE): dx = (x - center) / dx_range + dx_start dy = (y - center) / dy_range + dy_start a = dx b = dy for t in range(iterations): d = (a * a) - (b * b) + dx b = 2 * (a * b) + dy a = d h = d > max_value if h is True: mat[x, y] = t colored_mat = cm(mat / mat.max()) im = Image.fromarray((colored_mat * 255).astype(np.uint8)) path = f\"mandelbrot_{i}.png\" im.save(path) return path def generate(state): state.i = state.i + 1 state.path = generate_mandelbrot( dx_start=-state.dx_start / 100, dy_start=(state.dy_start - 100) / 100, iterations=state.iterations, i=state.i, ) i = 0 dx_start = 11 dy_start = 17 iterations = 50 path = generate_mandelbrot( dx_start=-dx_start / 100, dy_start=(dy_start - 100) / 100, ) page = \"\"\" # Mandelbrot Generator <|layout|columns=35 65| Display image from path <|{path}|image|width=500px|height=500px|class_name=img|> Iterations:<br /> Create a slider to select iterations <|{iterations}|slider|min=10|max=50|continuous=False|on_change=generate|><br /> X Position:<br /> <|{dy_start}|slider|min=0|max=100|continuous=False|on_change=generate|><br /> Y Position:<br /> Slider dx_start <|{dx_start}|slider|min=0|max=100|continuous=False|on_change=generate|><br /> |> \"\"\" Gui(page).run(title=\"Mandelbrot Generator\") "}
10
+ {"text": "# Create app to auto generate Tweeter status import logging import random import re # Import from 3rd party libraries from taipy.gui import Gui, notify, state import taipy # Import modules import oai # Configure logger logging.basicConfig(format=\"\\n%(asctime)s\\n%(message)s\", level=logging.INFO, force=True) def error_prompt_flagged(state, prompt): \"\"\"Notify user that a prompt has been flagged.\"\"\" notify(state, \"error\", \"Prompt flagged as inappropriate.\") logging.info(f\"Prompt flagged as inappropriate: {prompt}\") def error_too_many_requests(state): \"\"\"Notify user that too many requests have been made.\"\"\" notify( state, \"error\", \"Too many requests. Please wait a few seconds before generating another text or image.\", ) logging.info(f\"Session request limit reached: {state.n_requests}\") state.n_requests = 1 # Define functions def generate_text(state): \"\"\"Generate Tweet text.\"\"\" state.tweet = \"\" state.image = None # Check the number of requests done by the user if state.n_requests >= 5: error_too_many_requests(state) return # Check if the user has put a topic if state.topic == \"\": notify(state, \"error\", \"Please enter a topic\") return # Create the prompt and add a style or not if state.style == \"\": state.prompt = ( f\"Write a {state.mood}Tweet about {state.topic} in less than 120 characters \" f\"and with the style of {state.style}:\\n\\n\\n\\n\" ) else: state.prompt = f\"Write a {state.mood}Tweet about {state.topic} in less than 120 characters:\\n\\n\" # openai configured and check if text is flagged openai = oai.Openai() flagged = openai.moderate(state.prompt) if flagged: error_prompt_flagged(state, f\"Prompt: {state.prompt}\\n\") return else: # Generate the tweet state.n_requests += 1 state.tweet = openai.complete(state.prompt).strip().replace('\"', \"\") # Notify the user in console and in the GUI logging.info( f\"Topic: {state.prompt}{state.mood}{state.style}\\n\" f\"Tweet: {state.tweet}\" ) notify(state, \"success\", \"Tweet created!\") def generate_image(state): \"\"\"Generate Tweet image.\"\"\" notify(state, \"info\", \"Generating image...\") # Check the number of requests done by the user if state.n_requests >= 5: error_too_many_requests(state) return state.image = None # Creates the prompt prompt_wo_hashtags = re.sub(\"#[A-Za-z0-9_]+\", \"\", state.prompt) processing_prompt = ( \"Create a detailed but brief description of an image that captures \" f\"the essence of the following text:\\n{prompt_wo_hashtags}\\n\\n\" ) # Openai configured and check if text is flagged openai = oai.Openai() flagged = openai.moderate(processing_prompt) if flagged: error_prompt_flagged(state, processing_prompt) return else: state.n_requests += 1 # Generate the prompt that will create the image processed_prompt = ( openai.complete(prompt=processing_prompt, temperature=0.5, max_tokens=40) .strip() .replace('\"', \"\") .split(\".\")[0] + \".\" ) # Generate the image state.image = openai.image(processed_prompt) # Notify the user in console and in the GUI logging.info(f\"Tweet: {state.prompt}\\nImage prompt: {processed_prompt}\") notify(state, \"success\", f\"Image created!\") def feeling_lucky(state): \"\"\"Generate a feeling-lucky tweet.\"\"\" with open(\"moods.txt\") as f: sample_moods = f.read().splitlines() state.topic = \"an interesting topic\" state.mood = random.choice(sample_moods) state.style = \"\" generate_text(state) # Variables tweet = \"\" prompt = \"\" n_requests = 0 topic = \"AI\" mood = \"inspirational\" style = \"elonmusk\" image = None # Called whever there is a problem def on_exception(state, function_name: str, ex: Exception): logging.error(f\"Problem {ex} \\nin {function_name}\") notify(state, \"error\", f\"Problem {ex} \\nin {function_name}\") def update_documents(state: taipy.gui.state, docs: list[dict]) -> None: \"\"\" Updates a partial with a list of documents Args: state: The state of the GUI docs: A list of documents \"\"\" updated_part = \"\" for doc in docs: title = doc[\"title\"] summary = doc[\"summary\"] link = doc[\"link\"] updated_part += f\"\"\" <a href=\"{link}\" target=\"_blank\"> <h3>{title}</h3> </a> <p>{summary}</p> <br/> \"\"\" state.p.update_content(state, updated_part) # Markdown for the entire page ## <text| ## |text> ## \"text\" here is just a name given to my part/my section ## it has no meaning in the code page = \"\"\" <|container| # **Generate**{: .color-primary} Tweets This mini-app generates Tweets using OpenAI's GPT-3 based [Davinci model](https://beta.openai.com/docs/models/overview) for texts and [DALL\u00b7E](https://beta.openai.com/docs/guides/images) for images. You can find the code on [GitHub](https://github.com/Avaiga/demo-tweet-generation) and the original author on [Twitter](https://twitter.com/kinosal). <br/> <a href=\"{azaz}\" target=\"_blank\"> <h3>{sqdqs}</h3> </a> <p>{qfqffqs}</p> <br/> <|layout|columns=1 1 1|gap=30px|class_name=card| <topic| ## **Topic**{: .color-primary} (or hashtag) <|{topic}|input|label=Topic (or hashtag)|> |topic> <mood| ## **Mood**{: .color-primary} <|{mood}|input|label=Mood (e.g. inspirational, funny, serious) (optional)|> |mood> <style| ## Twitter **account**{: .color-primary} <|{style}|input|label=Twitter account handle to style-copy recent Tweets (optional)|> |style> Create a Generate text button <|Generate text|button|on_action=generate_text|label=Generate text|> <|Feeling lucky|button|on_action=feeling_lucky|label=Feeling Lucky|> |> <br/> --- <br/> ### Generated **Tweet**{: .color-primary} Create a text input for the tweet <|{tweet}|input|multiline|label=Resulting tweet|class_name=fullwidth|> <center><|Generate image|button|on_action=generate_image|label=Generate image|active={prompt!=\"\" and tweet!=\"\"}|></center> <image|part|render={prompt != \"\" and tweet != \"\" and image is not None}|class_name=card| ### **Image**{: .color-primary} from Dall-e Display image <center><|{image}|image|height=400px|></center> |image> Break line <br/> **Code from [@kinosal](https://twitter.com/kinosal)** Original code can be found [here](https://github.com/kinosal/tweet) |> \"\"\" if __name__ == \"__main__\": Gui(page).run(dark_mode=False, port=5089) "}