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+
'''
|
| 2 |
+
参考: https://github.com/shroominic/codeinterpreter-api
|
| 3 |
+
|
| 4 |
+
1. 可以存在本地,然后再调出来。 working.
|
| 5 |
+
1. 可以直接在内存中读出图片。
|
| 6 |
+
'''
|
| 7 |
+
# TODO:如何在内存中读取文件。
|
| 8 |
+
|
| 9 |
+
from codeinterpreterapi import CodeInterpreterSession, File
|
| 10 |
+
import streamlit as st
|
| 11 |
+
from codeinterpreterapi import CodeInterpreterSession
|
| 12 |
+
import openai
|
| 13 |
+
import os
|
| 14 |
+
import matplotlib.pyplot as plt
|
| 15 |
+
import pandas as pd
|
| 16 |
+
from io import StringIO
|
| 17 |
+
import csv
|
| 18 |
+
import tempfile
|
| 19 |
+
from tempfile import NamedTemporaryFile
|
| 20 |
+
import pathlib
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
os.environ["OPENAI_API_KEY"] = os.environ['user_token']
|
| 25 |
+
openai.api_key = os.environ['user_token']
|
| 26 |
+
os.environ["VERBOSE"] = "True" # 可以看到具体的错误?
|
| 27 |
+
|
| 28 |
+
# # #* 如果碰到接口问题,可以启用如下设置。
|
| 29 |
+
# openai.proxy = {
|
| 30 |
+
# "http": "http://127.0.0.1:7890",
|
| 31 |
+
# "https": "http://127.0.0.1:7890"
|
| 32 |
+
# }
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# st.title("ChatGPT-like clone")
|
| 36 |
+
st.title("Business Data Analytics by ChatGPT")
|
| 37 |
+
uploaded_file = st.file_uploader("Choose a file", type=(["csv","txt","xlsx","xls"]))
|
| 38 |
+
# uploaded_file = st.file_uploader("选择一个文件", type=(["csv","txt","xlsx","xls"]))
|
| 39 |
+
# st.write(uploaded_file)
|
| 40 |
+
if uploaded_file is not None:
|
| 41 |
+
# csv_file = csv.reader(uploaded_file)
|
| 42 |
+
csv_file = pd.read_csv(uploaded_file)
|
| 43 |
+
st.write(csv_file[:5]) ## 这里只是显示文件,后面需要定位文件所在的绝对路径。
|
| 44 |
+
|
| 45 |
+
uploaded_file_name = "File_provided"
|
| 46 |
+
temp_dir = tempfile.TemporaryDirectory()
|
| 47 |
+
uploaded_file_path = pathlib.Path(temp_dir.name) / uploaded_file_name #! working.
|
| 48 |
+
with open(uploaded_file_path, 'wb') as output_temporary_file:
|
| 49 |
+
# output_temporary_file.write(uploaded_file.read())
|
| 50 |
+
output_temporary_file.write(uploaded_file.getvalue()) #! 必须用这种格式读入内容,然后才可以写入temporary文件夹中。
|
| 51 |
+
st.write(uploaded_file_path) #* 可以查看文件是否真实存在,然后是否可以
|
| 52 |
+
|
| 53 |
+
### how to read data inside streamlit.
|
| 54 |
+
# # files = pd.read_csv(uploaded_file)
|
| 55 |
+
# bytes_data = uploaded_file.getvalue()
|
| 56 |
+
# # st.write(bytes_data)
|
| 57 |
+
|
| 58 |
+
# # To convert to a string based IO:
|
| 59 |
+
# stringio = StringIO(uploaded_file.getvalue().decode("utf-8"))
|
| 60 |
+
# # st.write(stringio)
|
| 61 |
+
|
| 62 |
+
# # To read file as string:
|
| 63 |
+
# string_data = stringio.read()
|
| 64 |
+
# # st.write(string_data)
|
| 65 |
+
|
| 66 |
+
# # Can be used wherever a "file-like" object is accepted:
|
| 67 |
+
# # dataframe = pd.read_csv(uploaded_file)
|
| 68 |
+
# files = pd.read_csv(uploaded_file, encoding='utf-8')
|
| 69 |
+
|
| 70 |
+
# openai.api_key = st.secrets["OPENAI_API_KEY"]
|
| 71 |
+
|
| 72 |
+
async def main():
|
| 73 |
+
if "openai_model" not in st.session_state:
|
| 74 |
+
# st.session_state["openai_model"] = "gpt-3.5-turbo"
|
| 75 |
+
st.session_state["openai_model"] = "gpt-4" ##NOTE: data analysis module must use GPT-4.
|
| 76 |
+
|
| 77 |
+
if "messages" not in st.session_state:
|
| 78 |
+
st.session_state.messages = []
|
| 79 |
+
|
| 80 |
+
for message in st.session_state.messages:
|
| 81 |
+
with st.chat_message(message["role"]):
|
| 82 |
+
st.markdown(message["content"])
|
| 83 |
+
|
| 84 |
+
if prompt := st.chat_input("What is up?"):
|
| 85 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 86 |
+
with st.chat_message("user"):
|
| 87 |
+
st.markdown(prompt)
|
| 88 |
+
|
| 89 |
+
with st.chat_message("assistant"):
|
| 90 |
+
message_placeholder = st.empty()
|
| 91 |
+
full_response = ""
|
| 92 |
+
|
| 93 |
+
###原始示例 https://docs.streamlit.io/knowledge-base/tutorials/build-conversational-apps
|
| 94 |
+
# for response in openai.ChatCompletion.create(
|
| 95 |
+
# model=st.session_state["openai_model"],
|
| 96 |
+
# messages=[
|
| 97 |
+
# {"role": m["role"], "content": m["content"]}
|
| 98 |
+
# for m in st.session_state.messages
|
| 99 |
+
# ],
|
| 100 |
+
# stream=True,
|
| 101 |
+
# ):
|
| 102 |
+
# full_response += response.choices[0].delta.get("content", "")
|
| 103 |
+
# message_placeholder.markdown(full_response + "▌")
|
| 104 |
+
|
| 105 |
+
async with CodeInterpreterSession() as session:
|
| 106 |
+
|
| 107 |
+
# user_request = "对于文件中的'SepalLengthCm’数据给我一个'直方图',提供图表,并给出分析结果"
|
| 108 |
+
#! 可以用设定dpi=300来输出高质量的图表。(注:图的解析度dpi设定为300)
|
| 109 |
+
environ_settings = "【背景要求】如果我没有告诉你任何定制化的要求,那么请按照以下的默认要求来回答:1. 你需要用提问的语言来回答(如:中文提问你就用中文来回答,英文提问你就用英文来回答)。2. 如果要求你输出图表,那么图的解析度dpi需要设定为300。图尽量使用seaborn库。seaborn库的参数设定:sns.set(rc={'axes.facecolor':'#FFF9ED','figure.facecolor':'#FFF9ED'}, palette='deep')。" ## seaborn中的palette参数可以设定图表的颜色,选项包括:deep, muted, pastel, bright, dark, colorblind,Spectral。更多参数可以参考:https://seaborn.pydata.org/generated/seaborn.color_palette.html。
|
| 110 |
+
|
| 111 |
+
user_request = environ_settings + "\n\n"+ "你需要完成以下任务:\n\n" + prompt
|
| 112 |
+
# print('user_request: \n', user_request)
|
| 113 |
+
|
| 114 |
+
# files = [
|
| 115 |
+
# # File.from_path("examples/assets/iris.csv"),
|
| 116 |
+
# # File.from_path("/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/ChatGPT讲课要点 copy.txt"),
|
| 117 |
+
# # File.from_path("/Users/yunshi/Downloads/360Data/文档/cars.csv"),
|
| 118 |
+
# # File.from_path("/Users/yunshi/Downloads/360Data/PhD Program/SAS邓祖新/SAS(邓祖新)/sasdata/sasdata/mydir/sasxls.xls"),
|
| 119 |
+
# # File.from_path("/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/Coding/code_interpreter/rawdata/时间频数统计.xlsx"),
|
| 120 |
+
# # File.from_path("/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/Coding/code_interpreter/rawdata/文献相关数据.xls"),
|
| 121 |
+
# File.from_path(
|
| 122 |
+
# "/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/Coding/code_interpreter/codeinterpreter-api-main/examples/assets/iris.csv"),
|
| 123 |
+
# ] # user_request = "对于文件中的【SepalLengthCm SepalWidthCm】数据,进行【IsolationForest】的异常值分析。你需要展示分析图表,并给出分析结果。最后,你要给出异常点的原始数据,"
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
### 加载上传的文件,主要路径在上面代码中。
|
| 127 |
+
files = [File.from_path(str(uploaded_file_path))]
|
| 128 |
+
|
| 129 |
+
### generate the response
|
| 130 |
+
response = await session.generate_response(
|
| 131 |
+
user_request, files=files
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# output to the user
|
| 135 |
+
print("AI: ", response.content)
|
| 136 |
+
full_response = response.content
|
| 137 |
+
### full_response = "this is full response"
|
| 138 |
+
|
| 139 |
+
# for file in response.files:
|
| 140 |
+
for i, file in enumerate(response.files):
|
| 141 |
+
# await file.asave(f"/Users/yunshi/Downloads/360Data/Data Center/Working-On Task/演讲与培训/2023ChatGPT/Coding/code_interpreter/output{i}.png") ##working.
|
| 142 |
+
st.image(file.get_image()) #! working.
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# message_placeholder.markdown(full_response + "▌") ## orignal code.
|
| 146 |
+
# message_placeholder.markdown(full_response) ## orignal code.
|
| 147 |
+
st.write(full_response)
|
| 148 |
+
await session.astop() #! 确认需要关闭。
|
| 149 |
+
|
| 150 |
+
st.session_state.messages.append(
|
| 151 |
+
{"role": "assistant", "content": full_response})
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
import asyncio
|
| 157 |
+
# * 也可以用命令执行这个python文件。’streamlit run frontend/app.py‘
|
| 158 |
+
asyncio.run(main())
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
codeinterpreterapi
|
| 2 |
+
openai
|
| 3 |
+
matplotlib
|
| 4 |
+
pandas
|
| 5 |
+
pathlib
|