Anupam202224 commited on
Commit
d1af361
·
verified ·
1 Parent(s): 2d9769a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -0
app.py CHANGED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import gradio as gr
4
+ from transformers import ReactCodeAgent, HfEngine, Tool
5
+ import pandas as pd
6
+ import spaces
7
+ import torch
8
+
9
+ from gradio import Chatbot
10
+ from streaming import stream_to_gradio
11
+ from huggingface_hub import login
12
+ from gradio.data_classes import FileData
13
+
14
+
15
+ llm_engine = HfEngine("meta-llama/Meta-Llama-3.1-70B-Instruct")
16
+
17
+ agent = ReactCodeAgent(
18
+ tools=[],
19
+ llm_engine=llm_engine,
20
+ additional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "seaborn", "scipy.stats"],
21
+ max_iterations=10,
22
+ )
23
+
24
+ base_prompt = """You are an expert data analyst.
25
+ According to the features you have and the data structure given below, determine which feature should be the target.
26
+ Then list 3 interesting questions that could be asked on this data, for instance about specific correlations with target variable.
27
+ Then answer these questions one by one, by finding the relevant numbers.
28
+ Meanwhile, plot some figures using matplotlib/seaborn and save them to the (already existing) folder './figures/': take care to clear each figure with plt.clf() before doing another plot.
29
+
30
+ In your final answer: summarize these correlations and trends
31
+ After each number derive real worlds insights, for instance: "Correlation between is_december and boredness is 1.3453, which suggest people are more bored in winter".
32
+ Your final answer should be a long string with at least 3 numbered and detailed parts.
33
+
34
+ Structure of the data:
35
+ {structure_notes}
36
+
37
+ The data file is passed to you as the variable data_file, it is a pandas dataframe, you can use it directly.
38
+ DO NOT try to load data_file, it is already a dataframe pre-loaded in your python interpreter!
39
+ """
40
+
41
+ example_notes="""This data is about the Titanic wreck in 1912.
42
+ The target figure is the survival of passengers, notes by 'Survived'
43
+ pclass: A proxy for socio-economic status (SES)
44
+ 1st = Upper
45
+ 2nd = Middle
46
+ 3rd = Lower
47
+ age: Age is fractional if less than 1. If the age is estimated, is it in the form of xx.5
48
+ sibsp: The dataset defines family relations in this way...
49
+ Sibling = brother, sister, stepbrother, stepsister
50
+ Spouse = husband, wife (mistresses and fiancés were ignored)
51
+ parch: The dataset defines family relations in this way...
52
+ Parent = mother, father
53
+ Child = daughter, son, stepdaughter, stepson
54
+ Some children travelled only with a nanny, therefore parch=0 for them."""
55
+
56
+ @spaces.GPU
57
+ def get_images_in_directory(directory):
58
+ image_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff'}
59
+
60
+ image_files = []
61
+ for root, dirs, files in os.walk(directory):
62
+ for file in files:
63
+ if os.path.splitext(file)[1].lower() in image_extensions:
64
+ image_files.append(os.path.join(root, file))
65
+ return image_files
66
+
67
+ @spaces.GPU
68
+ def interact_with_agent(file_input, additional_notes):
69
+ shutil.rmtree("./figures")
70
+ os.makedirs("./figures")
71
+
72
+ data_file = pd.read_csv(file_input)
73
+ data_structure_notes = f"""- Description (output of .describe()):
74
+ {data_file.describe()}
75
+ - Columns with dtypes:
76
+ {data_file.dtypes}"""
77
+
78
+ prompt = base_prompt.format(structure_notes=data_structure_notes)
79
+
80
+ if additional_notes and len(additional_notes) > 0:
81
+ prompt += "\nAdditional notes on the data:\n" + additional_notes
82
+
83
+ messages = [gr.ChatMessage(role="user", content=prompt)]
84
+ yield messages + [
85
+ gr.ChatMessage(role="assistant", content="⏳ _Starting task..._")
86
+ ]
87
+
88
+ plot_image_paths = {}
89
+ for msg in stream_to_gradio(agent, prompt, data_file=data_file):
90
+ messages.append(msg)
91
+ for image_path in get_images_in_directory("./figures"):
92
+ if image_path not in plot_image_paths:
93
+ image_message = gr.ChatMessage(
94
+ role="assistant",
95
+ content=FileData(path=image_path, mime_type="image/png"),
96
+ )
97
+ plot_image_paths[image_path] = True
98
+ messages.append(image_message)
99
+ yield messages + [
100
+ gr.ChatMessage(role="assistant", content="⏳ _Still processing..._")
101
+ ]
102
+ yield messages
103
+
104
+
105
+ with gr.Blocks(
106
+ theme=gr.themes.Soft(
107
+ primary_hue=gr.themes.colors.yellow,
108
+ secondary_hue=gr.themes.colors.blue,
109
+ )
110
+ ) as demo:
111
+ gr.Markdown("""# Llama-3.1 Data analyst 📊🤔
112
+
113
+ Drop a `.csv` file below, add notes to describe this data if needed, and **Llama-3.1-70B will analyze the file content and draw figures for you!**""")
114
+ file_input = gr.File(label="Your file to analyze")
115
+ text_input = gr.Textbox(
116
+ label="Additional notes to support the analysis"
117
+ )
118
+ submit = gr.Button("Run analysis!", variant="primary")
119
+ chatbot = gr.Chatbot(
120
+ label="Data Analyst Agent",
121
+ type="messages",
122
+ avatar_images=(
123
+ None,
124
+ "https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png",
125
+ ),
126
+ )
127
+ gr.Examples(
128
+ examples=[["./example/titanic.csv", example_notes]],
129
+ inputs=[file_input, text_input],
130
+ cache_examples=False
131
+ )
132
+
133
+ submit.click(interact_with_agent, [file_input, text_input], [chatbot])
134
+
135
+ if __name__ == "__main__":
136
+ demo.launch()