oh-my-dear-ai commited on
Commit
ad54bec
1 Parent(s): 398b32f

refactor(app): update task handling and Base64 conversion functions

Browse files
Files changed (1) hide show
  1. app.py +52 -38
app.py CHANGED
@@ -7,12 +7,18 @@ import plotly.graph_objects as go
7
  import matplotlib.pyplot as plt
8
  from PIL import Image
9
  from io import BytesIO
10
- import plotly.io as pio
11
 
12
- pio.renderers.default = "browser"
 
 
 
 
 
 
 
13
 
14
  df = pd.read_csv("herbologist_almanac_checklist_data.csv")
15
- columns_with_tasks = [
16
  "task1",
17
  "task2",
18
  "task3",
@@ -28,7 +34,7 @@ PLANTS = list(df["plant"].unique())
28
 
29
 
30
  def bin_ls2base64(ls):
31
- # 将二进制列表转换为二进制列表
32
  binary_str = "".join(str(n) for n in ls)
33
 
34
  # decimal_int = int(bin_str, 2)
@@ -38,59 +44,58 @@ def bin_ls2base64(ls):
38
 
39
 
40
  def base64_to_binary(base64_str):
41
- # 将base64字符串转换为二进制字符串
42
  if isinstance(base64_str, str):
 
43
  byte_str = base64.b64decode(base64_str)
44
  binary_str = bin(int.from_bytes(byte_str, byteorder="big"))[2:].zfill(
45
- len(columns_with_tasks) * len(PLANTS)
46
  )
47
  # ls = [int(n) for n in binary_str]
48
  return binary_str
49
 
 
 
 
 
 
50
 
51
  def parse_token(token):
52
- try:
53
- if not token: # 处理空字符串的情况
54
- token = "\x00"
55
-
56
- if len(token) > 0:
57
- payload = base64_to_binary(token)
58
- almanac_data: list = [int(n) for n in payload]
59
- # print(len(almanac_data))
60
- parsed_dict = {}
61
- for _, row in df.iterrows():
62
- parsed_dict[row["plant"]] = [
63
- almanac_data.pop() for _ in range(len(columns_with_tasks))
64
- ]
65
 
 
 
 
 
 
 
 
 
 
 
66
  return parsed_dict
67
- except Exception as e:
68
- print(e)
69
 
70
 
71
- # 定义一个简单的函数,接收DataFrame数据
72
  def process_data(*args):
73
  plot_library = args[-1]
74
  almanac_dict = dict(zip(PLANTS, args[:-1]))
75
 
76
- almanac_df = df.filter(items=["plant", "name"] + columns_with_tasks)
77
  almanac_bin_ls = []
78
  for pl in PLANTS:
79
- # TODO refactor by using len
80
- almanac_inp = almanac_dict[pl]
81
-
82
- almanac_bin = [0 for _ in range(len(columns_with_tasks))]
83
-
84
- for n in almanac_inp:
85
- almanac_bin[n] = 1
86
 
87
- almanac_bin_ls += almanac_bin
 
 
88
 
89
- for _, i in enumerate(almanac_inp):
90
- almanac_df.loc[almanac_df["plant"] == pl, columns_with_tasks[i]] = "✔"
91
 
92
  almanac_reverse_64 = bin_ls2base64(reversed(almanac_bin_ls))
93
 
 
94
  return (
95
  (
96
  generate_img_by_plotly(almanac_df.drop(columns=df.columns[0]))
@@ -107,7 +112,7 @@ def show_checkbox_groups(token):
107
  for index, row in df.iterrows():
108
  tasks = [
109
  row[col][0].upper() + row[col][1:]
110
- for col in columns_with_tasks
111
  if df.notnull().at[index, col]
112
  ]
113
  with gr.Row():
@@ -117,12 +122,13 @@ def show_checkbox_groups(token):
117
  value=[
118
  tasks[i]
119
  for i, v in enumerate(parsed_dict[row["plant"]])
120
- if v == 1 and df.notnull().at[index, columns_with_tasks[i]]
121
  ],
122
  type="index",
123
  )
124
  checklist_inputs.append(checkbox)
125
 
 
126
  return checklist_inputs
127
 
128
 
@@ -170,9 +176,8 @@ def generate_img_by_matplotlib(df):
170
  if cell.get_text().get_text() == "nan":
171
  cell.set_text_props(text="", ha="center")
172
  if row == 0:
173
- text = cell.get_text().get_text()
174
  cell.set_text_props(
175
- text=text, weight="bold", ha="center"
176
  ) # Bold and center-align header text
177
  if col == 0:
178
  text = cell.get_text().get_text()
@@ -204,6 +209,7 @@ def generate_img_by_matplotlib(df):
204
  buffer.seek(0)
205
  image = Image.open(buffer)
206
 
 
207
  return image
208
 
209
 
@@ -326,6 +332,7 @@ def generate_img_by_plotly(df):
326
  buffer.seek(0)
327
  image = Image.open(buffer)
328
 
 
329
  return image
330
 
331
 
@@ -365,7 +372,7 @@ with gr.Blocks() as app:
365
  plot_library = gr.Radio(
366
  ["plotly", "matplotlib"],
367
  label="Plot Library",
368
- value=""plotly",
369
  info="Choose your plot library",
370
  )
371
 
@@ -382,6 +389,7 @@ with gr.Blocks() as app:
382
  - 2024/09/03: Fix a mistake in the tasks of mimbulus
383
  - 2024/09/04: Correct Radiant count for water hyacinth
384
  - 2024/09/05: Support image generated by plotly
 
385
  """
386
  )
387
 
@@ -397,6 +405,12 @@ with gr.Blocks() as app:
397
  outputs=checklist_inputs,
398
  )
399
 
 
 
 
 
 
 
400
 
401
  app.queue()
402
  app.launch()
 
7
  import matplotlib.pyplot as plt
8
  from PIL import Image
9
  from io import BytesIO
 
10
 
11
+ # import logging
12
+
13
+ # import plotly.io as pio
14
+
15
+ # pio.renderers.default = "browser"
16
+
17
+ # logger = logging.getLogger(__name__)
18
+ # logger.setLevel(logging.INFO)
19
 
20
  df = pd.read_csv("herbologist_almanac_checklist_data.csv")
21
+ TASKS = [
22
  "task1",
23
  "task2",
24
  "task3",
 
34
 
35
 
36
  def bin_ls2base64(ls):
37
+ # 将二进制列表转换为base64字符串
38
  binary_str = "".join(str(n) for n in ls)
39
 
40
  # decimal_int = int(bin_str, 2)
 
44
 
45
 
46
  def base64_to_binary(base64_str):
 
47
  if isinstance(base64_str, str):
48
+ # 将base64字符串转换为二进制列表
49
  byte_str = base64.b64decode(base64_str)
50
  binary_str = bin(int.from_bytes(byte_str, byteorder="big"))[2:].zfill(
51
+ len(TASKS) * len(PLANTS)
52
  )
53
  # ls = [int(n) for n in binary_str]
54
  return binary_str
55
 
56
+ else:
57
+ raise TypeError(
58
+ "Invalid input type. Expected str, got {}".format(type(base64_str))
59
+ )
60
+
61
 
62
  def parse_token(token):
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
+ if not token: # 处理空字符串的情况
65
+ token = "\x00"
66
+
67
+ if len(token) > 0:
68
+ payload = base64_to_binary(token)
69
+ almanac_data: list = [int(n) for n in payload]
70
+ # print(len(almanac_data))
71
+ parsed_dict = {}
72
+ for _, row in df.iterrows():
73
+ parsed_dict[row["plant"]] = [almanac_data.pop() for _ in range(len(TASKS))]
74
  return parsed_dict
75
+ else:
76
+ return parse_token("\x00")
77
 
78
 
79
+ # 定义一个简单的函数,模拟接收DataFrame数据
80
  def process_data(*args):
81
  plot_library = args[-1]
82
  almanac_dict = dict(zip(PLANTS, args[:-1]))
83
 
84
+ almanac_df = df.filter(items=["plant", "name"] + TASKS)
85
  almanac_bin_ls = []
86
  for pl in PLANTS:
87
+ plant_tasks = almanac_dict[pl]
88
+ plant_tasks_done = [0 for _ in range(len(TASKS))]
 
 
 
 
 
89
 
90
+ for n, i in enumerate(plant_tasks):
91
+ plant_tasks_done[n] = 1
92
+ almanac_df.loc[almanac_df["plant"] == pl, TASKS[i]] = "✔"
93
 
94
+ almanac_bin_ls += plant_tasks_done
 
95
 
96
  almanac_reverse_64 = bin_ls2base64(reversed(almanac_bin_ls))
97
 
98
+ # logger.info("Generating image!")
99
  return (
100
  (
101
  generate_img_by_plotly(almanac_df.drop(columns=df.columns[0]))
 
112
  for index, row in df.iterrows():
113
  tasks = [
114
  row[col][0].upper() + row[col][1:]
115
+ for col in TASKS
116
  if df.notnull().at[index, col]
117
  ]
118
  with gr.Row():
 
122
  value=[
123
  tasks[i]
124
  for i, v in enumerate(parsed_dict[row["plant"]])
125
+ if v == 1 and df.notnull().at[index, TASKS[i]]
126
  ],
127
  type="index",
128
  )
129
  checklist_inputs.append(checkbox)
130
 
131
+ # logger.info("Rerendering checklist!")
132
  return checklist_inputs
133
 
134
 
 
176
  if cell.get_text().get_text() == "nan":
177
  cell.set_text_props(text="", ha="center")
178
  if row == 0:
 
179
  cell.set_text_props(
180
+ weight="bold", ha="center"
181
  ) # Bold and center-align header text
182
  if col == 0:
183
  text = cell.get_text().get_text()
 
209
  buffer.seek(0)
210
  image = Image.open(buffer)
211
 
212
+ # logger.info("Image generated by matplotlib successfully!")
213
  return image
214
 
215
 
 
332
  buffer.seek(0)
333
  image = Image.open(buffer)
334
 
335
+ # logger.info("Image generated by plotly successfully!")
336
  return image
337
 
338
 
 
372
  plot_library = gr.Radio(
373
  ["plotly", "matplotlib"],
374
  label="Plot Library",
375
+ value="plotly",
376
  info="Choose your plot library",
377
  )
378
 
 
389
  - 2024/09/03: Fix a mistake in the tasks of mimbulus
390
  - 2024/09/04: Correct Radiant count for water hyacinth
391
  - 2024/09/05: Support image generated by plotly
392
+ - 2024/09/13: Update Water Lily tasks and color options
393
  """
394
  )
395
 
 
405
  outputs=checklist_inputs,
406
  )
407
 
408
+ # generate_button.click(
409
+ # generate_img,
410
+ # inputs=[df_out],
411
+ # outputs=[generated_img],
412
+ # )
413
+
414
 
415
  app.queue()
416
  app.launch()