从pandasai捕获图像响应作为flask API响应

a1o7rhls  于 2023-11-15  发布在  其他
关注(0)|答案(3)|浏览(168)

我试图利用pandasai生成基于输入的图表。然后使用flask API公开生成的图像响应。

from pandasai import PandasAI
from pandasai.llm.openai import OpenAI
import pandas as pd
import os
from flask import send_file, request, jsonify
from flask import Flask
import numpy as np #The Python numerical algebra package
import pandas as pd #For working with data frames
import io as io
import matplotlib.pyplot as plt

app = Flask(__name__)

port = int(os.environ.get('PORT', 3000))

@app.route('/gdpChart/')
def getChart():
    #Accessing the language model of OpenAI through key
    llm = OpenAI(api_token='<<<<<my_api_token>>>>')
    #Passing the language model to pandasai
    pandas_ai = PandasAI(llm)
    df1 = pd.DataFrame({
    "country": ["United States", "United Kingdom", "France", "Germany", "Italy", "Spain", "Canada", "Australia", "Japan", "China"],
    "gdp": [21400000, 2940000, 2830000, 3870000, 2160000, 1350000, 1780000, 1320000, 516000, 14000000],
    "happiness_index": [7.3, 7.2, 6.5, 7.0, 6.0, 6.3, 7.3, 7.3, 5.9, 5.0]
    })
    # Enter Prompt related to data or Select from Pre-defined for demo purposes.
    prompt = 'Plot the piechart of countries showing for each the gpd, using different colors for each bar'
    response = pandas_ai.run(df1, prompt=prompt,
                          is_conversational_answer=False)

    # bytes_image = io.BytesIO()
    # plt.savefig(bytes_image, format='png')
    # bytes_image.seek(0)
    # return send_file(bytes_image, mimetype='image/jpeg')
    return send_file(response, mimetype='image/jpeg')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port)

字符串
在这里,pandas_ai.run()在调用API url http://localhost:3000/gdpChart时会弹出一张图片,但是我无法将此图片设置为对API的响应。
我的问题是:如何将图像响应(来自pandasai)设置为flaskapi响应,以便图像在浏览器中显示为响应..
你好,法迪

waxmsbnn

waxmsbnn1#

您可以通过在PandasAI构造函数中将save_charts参数设置为True来保存PandasAI生成的任何图表。

pandas_ai = PandasAI(llm, save_charts=True, save_charts_path="resources/")

字符串
我做了类似的事情,在提示符中直接告诉它保存图形,然后我提供该文件。

prompt = 'Save as plot.png a plot the piechart of countries showing for each the gpd, using different colors for each bar'

lmyy7pcs

lmyy7pcs2#

你可以这样写一个prompt,它返回base64 of graph image,也就是在最后打印base64 of graph image,然后你直接把base64发送到前端,在响应中返回。

resQuery+="''' first clear the previous plt, at last always convert the graph image to base64 value and do not forget to print the Base64 value '''"
res= pandas_ai.run(df, prompt=resQuery)
res=res.decode('utf-8')
return res

字符串
在前端,你可以用JS轻松解码base64。
我也做了同样的事情,它对我来说工作得很好。而且它也很快,首先保存图表,然后通过os阅读并进一步发送。

vfwfrxfs

vfwfrxfs3#

要做到这一点,关键是将图表保存在特定目录,然后将其复制到静态文件夹中,以便flask获取并显示它。在您的后端,您可以通过检查响应的类型来了解pandasai何时返回图表。当您的查询涉及生成图表时,response为 None。如果您愿意,可以捕获其他响应类型(如文本或表格)并呈现它们。
这就是我如何让它工作:

# Load in the smart df
def getChart():
    #Accessing the language model of OpenAI through key
    llm = OpenAI(api_token='<<<<<my_api_token>>>>')
    #Passing the language model to pandasai
    pandas_ai = PandasAI(llm, save_charts_path="path/to/saved_chart")
    df1 = pd.DataFrame({
    "country": ["United States", "United Kingdom", "France", "Germany", "Italy", "Spain", "Canada", "Australia", "Japan", "China"],
    "gdp": [21400000, 2940000, 2830000, 3870000, 2160000, 1350000, 1780000, 1320000, 516000, 14000000],
    "happiness_index": [7.3, 7.2, 6.5, 7.0, 6.0, 6.3, 7.3, 7.3, 5.9, 5.0]
    })
    # Enter Prompt related to data or Select from Pre-defined for demo purposes.
    prompt = 'Plot the piechart of countries showing for each the gpd, using different colors for each bar'
    response = pandas_ai.run(df1, prompt=prompt,
                          is_conversational_answer=False)

    # When your query involves generating a chart, response is None
    # You can catch other response types (like text or table) if you like and present them
    if response is None:
        try:
            shutil.copy(
                "path/to/saved_chart/temp_chart.png", "static/temp_chart.png"
            )
            return render_template(
                "home.html",
                message="Chart displayed!"
            )
        except Exception as e:
            print(e)
            return render_template(
                "home.html",
                message="Something went wrong! Please try again.",
            )
    else:
        return render_template(
                "home.html",
                message="Pandas AI didn't return a chart!"
            )

字符串
请注意,temp_chart.png可能会在不同的环境中发生变化,例如在Docker容器中。请确保您使用正确的文件名。
如果你想在一个html页面上显示图像(例如,home.html):

<!doctype html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>

  <img src="static/temp_chart.png" alt="Graph" style="width:100%">
  <p>{{message}}</p>

</body>

</html>

相关问题