Yannael commited on
Commit
c55e340
·
verified ·
1 Parent(s): e7d7176

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -52
app.py CHANGED
@@ -1,64 +1,114 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
27
 
28
- response = ""
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
41
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import pandas as pd
3
 
 
 
 
 
4
 
5
 
6
+ def get_data_product_id_from_table(evt: gr.SelectData):
 
 
 
 
 
 
 
 
7
 
8
+ id=evt.value
 
 
 
 
9
 
10
+ return get_data_product_id(id)
11
 
12
+ def get_data_product_id(id):
13
 
14
+ print(id)
 
 
 
 
 
 
 
15
 
16
+ image_path_front = dataset_merged_df.loc[dataset_merged_df['ID'] == id, 'Front photo'].values[0]
17
+ image_path_ingredients = dataset_merged_df.loc[dataset_merged_df['ID'] == id, 'Ingredients photo'].values[0]
18
+ image_path_nutritionals = dataset_merged_df.loc[dataset_merged_df['ID'] == id, 'Nutritionals photo'].values[0]
19
 
20
+ features = ['brand', 'product_name', 'ingredients', 'energy_kj', 'energy_kcal', 'fat', 'saturated_fat', 'carbohydrates', 'sugars', 'fibers', 'proteins', 'salt']
21
 
22
+ data = []
23
+
24
+ for feature in features:
25
+ product_values = dataset_merged_df.loc[dataset_merged_df['ID'] == id, [f'Reference_{feature}',f'Predicted_{feature}',f'accuracy_score_{feature}']]
26
+ product_values_list = product_values.values.flatten().tolist()
27
+ data.append([feature]+product_values_list)
28
+
29
+ data = pd.DataFrame(data, columns=['Feature', 'Reference value', 'Predicted value', 'Accuracy score'])
30
+ gradients = 1-data['Accuracy score']
31
+
32
+ data = data.map(lambda x: f'{x:g}' if isinstance(x, float) else x)
33
+ data = data.style.background_gradient(axis=0, gmap=gradients, cmap='summer', vmin=0, vmax=1)
34
+
35
+ plots = [image_path_front, image_path_ingredients, image_path_nutritionals]
36
+
37
+ return {data_df: data,
38
+ data_plot: plots,
39
+ }
40
+
41
+ def load_data(filepath):
42
+
43
+ global dataset_merged_df
44
+ global dataset_metadata
45
+
46
+ dataset_merged_df = pd.read_csv(f"{filepath}")
47
+ dataset_merged_df['mean_accuracy_score'] = dataset_merged_df.filter(regex='^accuracy_score').mean(axis=1)
48
+
49
+ dataset_df = dataset_merged_df[['ID', 'Reference_brand', 'Reference_product_name', 'mean_accuracy_score']].copy()
50
+ dataset_df = dataset_df.style.background_gradient(axis=0, gmap=1-dataset_df['mean_accuracy_score'], cmap='summer', vmin=0, vmax=1)
51
+
52
+ return dataset_df
53
+
54
+ def toggle_row_visibility(show):
55
+ if show:
56
+ return gr.update(visible=True)
57
+ else:
58
+ return gr.update(visible=False)
59
+
60
+ # Custom CSS to set max height for the rows
61
+ custom_css = """
62
+ .dataframe-wrap {
63
+ max-height: 300px; /* Set the desired height */
64
+ overflow-y: scroll;
65
+ }
66
  """
67
+
68
+ with gr.Blocks(css=custom_css) as demo:
69
+
70
+ gr.HTML("<div align='center'><h1>Euroconsumers Food Data Lake</h1>")
71
+ gr.HTML("<div align='center'><h2>Food data processing</h2>")
72
+
73
+ with gr.Row():
74
+ file_input = gr.File(label="Upload CSV File", type="filepath")
75
+
76
+ with gr.Row(visible=False) as dataset_block:
77
+ with gr.Column():
78
+ gr.HTML("<h2>Dataset summary</h2>")
79
+ with gr.Row():
80
+ gr.HTML("Click on a product ID (FIRST COLUMN) in the table to view product details")
81
+
82
+ # Display summary of the dataset - ID, Reference_brand, Reference_product_name, mean_accuracy_score
83
+ with gr.Row(elem_classes="dataframe-wrap"):
84
+ dataframe_component = gr.DataFrame()
85
+
86
+ with gr.Row(visible=False) as product_detail_block:
87
+ with gr.Column():
88
+ # Section for product details
89
+ gr.HTML("<h2>Product details</h2>")
90
+
91
+ # Display product photos
92
+ data_plot = gr.Gallery(label="Product photos", show_label=True, elem_id="gallery"
93
+ , columns=[3], rows=[1], object_fit="contain", height="auto")
94
+ # Display product data
95
+ # https://github.com/gradio-app/gradio/pull/5894
96
+ data_df = gr.Dataframe(label="Product data", scale=2,
97
+ column_widths=["10%", "40%", "40%", "10%"],
98
+ wrap=True)
99
+
100
+ ### Control functions
101
+
102
+ # Linking the select_dataset change event to update both the gradio DataFrame and product_ids dropdown
103
+ file_input.change(load_data, inputs=file_input, outputs=dataframe_component)
104
+ # Toggle visibility of the dataset block
105
+ file_input.change(toggle_row_visibility, inputs=file_input, outputs=dataset_block)
106
+
107
+ # Update the product data and plots when a product ID is clicked in the dataframe
108
+ dataframe_component.select(fn=get_data_product_id_from_table, outputs=[data_df, data_plot])
109
+ # Toggle visibility of the product detail block
110
+ dataframe_component.select(toggle_row_visibility, inputs=file_input, outputs=product_detail_block)
111
+
112
+ demo.launch(debug=True)
113
+
114
+