import functions_framework from flask import Flask, jsonify, send_file from flask_cors import CORS import matplotlib.pyplot as plt from matplotlib.backends.backend_svg import FigureCanvasSVG import io import os import torch app = Flask(__name__) CORS(app) def create_svg_plot(): weight = 0.7 bias = 0.3 start = 0 end = 1 step = 0.02 X = torch.arange(start, end, step).unsqueeze(dim=1) Y = weight * X + bias # print(Y) x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] fig, ax = plt.subplots() ax.plot(x, y) ax.set_title('Sample Plot') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') svg_output = io.StringIO() canvas = FigureCanvasSVG(fig) canvas.print_svg(svg_output) # Close the plot to free up resources plt.close(fig) return svg_output.getvalue() @functions_framework.http def curvefit(request): """HTTP Cloud Function. Args: request (flask.Request): The request object. Returns: The response text, or any set of values that can be turned into a Response object using `make_response` . """ if request.method == 'OPTIONS': headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', # 'Access-Control-Max-Age': '3600' } return ('', 204, headers) headers = { 'Access-Control-Allow-Origin': '*' } svg_plot = create_svg_plot() output_path = os.getcwd() + "/" + "plot.svg" with open(output_path,'rb') as f: file_data = io.BytesIO(f.read()) # return (jsonify({"plot": svg_plot}), 200, headers) return send_file(file_data, as_attachment=False, download_name= "plot.svg", mimetype='image/svg+xml')