Skip to content

Commit 85b4a32

Browse files
Update app.py
1 parent e0b837a commit 85b4a32

File tree

1 file changed

+34
-18
lines changed

1 file changed

+34
-18
lines changed

backend/app.py

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from datetime import datetime
1515
import tempfile
1616
import atexit
17+
import textwrap
1718
from reportlab.lib.pagesizes import letter
1819
from reportlab.pdfgen import canvas
1920
from reportlab.lib.units import inch
@@ -42,6 +43,7 @@ def log_print(*args):
4243
print(*args, file=log_stream)
4344
sys.stdout.flush()
4445

46+
# ========== PDF REPORT ==========
4547
def generate_pdf_report(summary, r2, mse, forecast_dict):
4648
c = canvas.Canvas(REPORT_PATH, pagesize=letter)
4749
width, height = letter
@@ -59,7 +61,8 @@ def generate_pdf_report(summary, r2, mse, forecast_dict):
5961
text.textLine("OpenAI Data Summary:")
6062
text.setFont("Helvetica", 9)
6163
for line in summary.splitlines():
62-
text.textLine(line)
64+
for wrapped in textwrap.wrap(line, width=100):
65+
text.textLine(wrapped)
6366

6467
text.textLine("")
6568
text.setFont("Helvetica-Bold", 12)
@@ -73,6 +76,32 @@ def generate_pdf_report(summary, r2, mse, forecast_dict):
7376
c.drawImage(FORECAST_PLOT_PATH, 1 * inch, 1 * inch, width=5.5 * inch, preserveAspectRatio=True)
7477
c.save()
7578

79+
# ========== FORECAST PLOT ==========
80+
def plot_forecast_with_axis(X, y, model, values_parsed, y_future, use_dates):
81+
x_min, x_max = min(X.min(), values_parsed.min()), max(X.max(), values_parsed.max())
82+
x_plot = np.linspace(x_min, x_max, 200).reshape(-1, 1)
83+
y_plot = model.predict(x_plot)
84+
85+
plt.figure()
86+
plt.scatter(X, y, label='Training Data', alpha=0.6)
87+
plt.plot(x_plot, y_plot, color='blue', label='Linear Regression')
88+
plt.scatter(values_parsed, y_future, color='red', label='Forecast', marker='x')
89+
plt.legend()
90+
plt.xlabel('X')
91+
plt.ylabel('Y')
92+
plt.title('Forecast with Linear Regression')
93+
94+
if use_dates:
95+
ticks = np.linspace(x_min, x_max, 6)
96+
labels = [datetime.fromordinal(int(t)).strftime('%Y-%m-%d') for t in ticks]
97+
plt.xticks(ticks, labels, rotation=45)
98+
99+
plt.tight_layout()
100+
plt.savefig(FORECAST_PLOT_PATH)
101+
plt.close()
102+
103+
# ========== ROUTES ==========
104+
76105
@app.route("/get-columns", methods=["POST"])
77106
def get_columns():
78107
file = request.files.get("file")
@@ -105,8 +134,9 @@ def upload_file():
105134

106135
df = df[[x_col, y_col]].dropna()
107136
df.columns = ['X', 'Y']
108-
log_print("Cleaned Data:\n\n", df.head())
137+
log_print("Data Cleaned using Pandas:\n\n Printing Header:\n", df.head())
109138

139+
# Plot original data
110140
plt.figure()
111141
plt.scatter(df['X'], df['Y'])
112142
plt.xlabel('X')
@@ -129,7 +159,7 @@ def upload_file():
129159
y_pred = model.predict(X)
130160
r2 = r2_score(y, y_pred)
131161
mse = mean_squared_error(y, y_pred)
132-
log_print(f"Model Trained. R² = {r2:.4f}, MSE = {mse:.4f}")
162+
log_print(f"\n\n Model Trained with Scikit-Learn: \n R² = {r2:.4f}, MSE = {mse:.4f}")
133163

134164
try:
135165
openai.api_key = os.getenv("OPENAI_API_KEY")
@@ -191,21 +221,7 @@ def predict():
191221
for x, p in zip(values_parsed.flatten(), y_future)
192222
}
193223

194-
x_min, x_max = min(X.min(), values_parsed.min()), max(X.max(), values_parsed.max())
195-
x_plot = np.linspace(x_min, x_max, 200).reshape(-1, 1)
196-
y_plot = model.predict(x_plot)
197-
198-
plt.figure()
199-
plt.scatter(X, y, label='Training Data', alpha=0.6)
200-
plt.plot(x_plot, y_plot, color='blue', label='Regression Line')
201-
plt.scatter(values_parsed, y_future, color='red', label='Forecast', marker='x')
202-
plt.legend()
203-
plt.xlabel('X')
204-
plt.ylabel('Y')
205-
plt.title('Forecast with Regression Line')
206-
plt.savefig(FORECAST_PLOT_PATH)
207-
plt.close()
208-
224+
plot_forecast_with_axis(X, y, model, values_parsed, y_future, use_dates)
209225
generate_pdf_report(cached_summary, r2_score(y, model.predict(X)), mean_squared_error(y, model.predict(X)), result)
210226

211227
return jsonify({

0 commit comments

Comments
 (0)