Skip to content

Commit 0f096fd

Browse files
Update app.py
1 parent 4b4f8f6 commit 0f096fd

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

backend/app.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,25 @@
1111
import numpy as np
1212
import openai
1313
from datetime import datetime
14+
import tempfile
15+
import atexit
16+
17+
# === CONFIG ===
18+
BACKEND_BASE_URL = "https://ai-dslab-backend-cpf2feachnetbbck.westus-01.azurewebsites.net"
1419

1520
# Initialize Flask app
1621
app = Flask(__name__)
1722
CORS(app) # Enable CORS for all routes
1823

19-
# Directories
20-
UPLOAD_FOLDER = "uploads"
21-
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
24+
# Use a secure temporary directory
25+
TEMP_DIR = tempfile.TemporaryDirectory()
26+
UPLOAD_FOLDER = TEMP_DIR.name
27+
PLOT_PATH = os.path.join(UPLOAD_FOLDER, "plot.png")
28+
29+
# Cleanup temp directory on shutdown
30+
@atexit.register
31+
def cleanup_temp_dir():
32+
TEMP_DIR.cleanup()
2233

2334
# Capture logs
2435
log_stream = io.StringIO()
@@ -57,7 +68,7 @@ def upload_file():
5768
plt.xlabel('X')
5869
plt.ylabel('Y')
5970
plt.title('Scatter Plot')
60-
plt.savefig("plot.png")
71+
plt.savefig(PLOT_PATH)
6172
plt.close()
6273
log_print("📊 Scatter plot saved.")
6374

@@ -101,13 +112,13 @@ def upload_file():
101112
"summary": summary,
102113
"log": log_stream.getvalue(),
103114
"forecast": "Submit future x-values below to get predictions.",
104-
"plot_url": request.url_root + "plot.png"
115+
"plot_url": f"{BACKEND_BASE_URL}/plot.png"
105116
})
106117

107118
# Serve the generated plot
108119
@app.route("/plot.png")
109120
def serve_plot():
110-
return send_file("plot.png", mimetype="image/png")
121+
return send_file(PLOT_PATH, mimetype="image/png")
111122

112123
# Handle prediction requests
113124
@app.route("/predict", methods=["POST"])
@@ -132,8 +143,14 @@ def predict():
132143
})
133144

134145
try:
135-
filename = os.listdir(UPLOAD_FOLDER)[0]
136-
df = pd.read_csv(os.path.join(UPLOAD_FOLDER, filename))
146+
files = os.listdir(UPLOAD_FOLDER)
147+
if not files:
148+
raise FileNotFoundError("No uploaded file found.")
149+
latest_file = max(
150+
[os.path.join(UPLOAD_FOLDER, f) for f in files if f.endswith(".csv")],
151+
key=os.path.getctime
152+
)
153+
df = pd.read_csv(latest_file)
137154
df.dropna(inplace=True)
138155
df.columns = ['X', 'Y']
139156
df['X'] = pd.to_datetime(df['X'], errors='coerce')
@@ -154,7 +171,7 @@ def predict():
154171
return jsonify({
155172
"forecast": result,
156173
"log": log_stream.getvalue(),
157-
"plot_url": request.url_root + "plot.png"
174+
"plot_url": f"{BACKEND_BASE_URL}/plot.png"
158175
})
159176

160177
except Exception as e:

0 commit comments

Comments
 (0)