Athspi commited on
Commit
ea92302
·
verified ·
1 Parent(s): 8143c6f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -16
app.py CHANGED
@@ -2,15 +2,22 @@ import os
2
  import zipfile
3
  import uuid
4
  import google.generativeai as genai
5
- from flask import Flask, request, jsonify, render_template, session, send_from_directory
 
6
  from dotenv import load_dotenv
7
 
8
  # --- API and App Configuration ---
9
- load_dotenv() # Load environment variables from .env file
10
 
11
- # Initialize the Flask app
12
  app = Flask(__name__)
13
- app.secret_key = os.environ.get("FLASK_SECRET_KEY", 'default-insecure-secret-key')
 
 
 
 
 
 
 
14
 
15
  # Configure the Gemini API client
16
  try:
@@ -30,11 +37,12 @@ UPLOAD_FOLDER = 'uploads'
30
  app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
31
  if not os.path.exists(UPLOAD_FOLDER):
32
  os.makedirs(UPLOAD_FOLDER)
 
 
33
 
34
 
35
- # --- Helper Functions ---
36
  def get_project_files(project_path):
37
- """Gets the file tree and content of all files in the project directory."""
38
  file_data = {}
39
  for root, _, files in os.walk(project_path):
40
  for file in files:
@@ -53,7 +61,6 @@ def get_project_files(project_path):
53
  # --- Flask Routes ---
54
  @app.route('/')
55
  def index():
56
- """Renders the main page and initializes the session."""
57
  if 'project_id' not in session:
58
  session['project_id'] = str(uuid.uuid4())
59
  session['chat_history'] = []
@@ -62,7 +69,6 @@ def index():
62
 
63
  @app.route('/upload', methods=['POST'])
64
  def upload_project():
65
- """Handles the project zip file upload."""
66
  if 'project_id' not in session:
67
  session['project_id'] = str(uuid.uuid4())
68
  session['chat_history'] = []
@@ -78,15 +84,16 @@ def upload_project():
78
  project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
79
  if not os.path.exists(project_path):
80
  os.makedirs(project_path)
81
-
82
  zip_path = os.path.join(project_path, file.filename)
83
  file.save(zip_path)
84
-
85
  with zipfile.ZipFile(zip_path, 'r') as zip_ref:
86
  zip_ref.extractall(project_path)
87
  os.remove(zip_path)
88
 
89
  project_files = get_project_files(project_path)
 
 
 
90
  initial_context = "The user has uploaded a new project. Here is the file structure and content:\n\n"
91
  for path, content in project_files.items():
92
  initial_context += f"**File:** `{path}`\n```\n{content}\n```\n\n"
@@ -109,9 +116,12 @@ def upload_project():
109
  return jsonify({"error": "Invalid file type. Please upload a .zip file."}), 400
110
 
111
 
 
 
 
 
112
  @app.route('/chat', methods=['POST'])
113
  def chat():
114
- """Handles chat interaction with the Gemini API."""
115
  if not model:
116
  return jsonify({"error": "Gemini API is not configured. Please check your API key."}), 500
117
 
@@ -127,7 +137,6 @@ def chat():
127
  session['chat_history'].append({"role": "user", "parts": [user_message]})
128
  session.modified = True
129
 
130
- # We send the history to the model
131
  chat_session = model.start_chat(history=session['chat_history'])
132
 
133
  try:
@@ -168,7 +177,6 @@ def chat():
168
 
169
  @app.route('/file_tree')
170
  def get_file_tree():
171
- """Returns the current file structure of the project."""
172
  project_id = session.get('project_id')
173
  if not project_id:
174
  return jsonify({"error": "No project in session."}), 400
@@ -180,7 +188,6 @@ def get_file_tree():
180
 
181
  @app.route('/file_content')
182
  def get_file_content():
183
- """Returns the content of a specific file."""
184
  project_id = session.get('project_id')
185
  file_path = request.args.get('path')
186
  if not project_id or not file_path:
@@ -198,7 +205,6 @@ def get_file_content():
198
 
199
  @app.route('/download')
200
  def download_project():
201
- """Zips and sends the current project state for download."""
202
  project_id = session.get('project_id')
203
  if not project_id:
204
  return "No project to download.", 404
@@ -215,4 +221,4 @@ def download_project():
215
 
216
 
217
  if __name__ == '__main__':
218
- app.run(host="0.0.0.0", port=7860)
 
2
  import zipfile
3
  import uuid
4
  import google.generativeai as genai
5
+ from flask import Flask, request, jsonify, render_template, session
6
+ from flask_session import Session # Import the extension
7
  from dotenv import load_dotenv
8
 
9
  # --- API and App Configuration ---
10
+ load_dotenv()
11
 
 
12
  app = Flask(__name__)
13
+ app.config["SECRET_KEY"] = os.environ.get("FLASK_SECRET_KEY", 'default-insecure-secret-key')
14
+
15
+ # --- SERVER-SIDE SESSION CONFIGURATION ---
16
+ app.config["SESSION_PERMANENT"] = False
17
+ app.config["SESSION_TYPE"] = "filesystem" # Store sessions on the server's filesystem
18
+ app.config['SESSION_FILE_DIR'] = './flask_session' # Directory to store session files
19
+ Session(app) # Initialize the session extension
20
+ # --- END OF SESSION CONFIGURATION ---
21
 
22
  # Configure the Gemini API client
23
  try:
 
37
  app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
38
  if not os.path.exists(UPLOAD_FOLDER):
39
  os.makedirs(UPLOAD_FOLDER)
40
+ if not os.path.exists('./flask_session'):
41
+ os.makedirs('./flask_session')
42
 
43
 
44
+ # --- Helper Functions (No Changes) ---
45
  def get_project_files(project_path):
 
46
  file_data = {}
47
  for root, _, files in os.walk(project_path):
48
  for file in files:
 
61
  # --- Flask Routes ---
62
  @app.route('/')
63
  def index():
 
64
  if 'project_id' not in session:
65
  session['project_id'] = str(uuid.uuid4())
66
  session['chat_history'] = []
 
69
 
70
  @app.route('/upload', methods=['POST'])
71
  def upload_project():
 
72
  if 'project_id' not in session:
73
  session['project_id'] = str(uuid.uuid4())
74
  session['chat_history'] = []
 
84
  project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
85
  if not os.path.exists(project_path):
86
  os.makedirs(project_path)
 
87
  zip_path = os.path.join(project_path, file.filename)
88
  file.save(zip_path)
 
89
  with zipfile.ZipFile(zip_path, 'r') as zip_ref:
90
  zip_ref.extractall(project_path)
91
  os.remove(zip_path)
92
 
93
  project_files = get_project_files(project_path)
94
+ # DESIGN IMPROVEMENT: No longer store project files in the session.
95
+ # We read them from disk when needed. This was a major cause of the large cookie.
96
+
97
  initial_context = "The user has uploaded a new project. Here is the file structure and content:\n\n"
98
  for path, content in project_files.items():
99
  initial_context += f"**File:** `{path}`\n```\n{content}\n```\n\n"
 
116
  return jsonify({"error": "Invalid file type. Please upload a .zip file."}), 400
117
 
118
 
119
+ # The rest of the file (chat, file_tree, file_content, download routes)
120
+ # remains the same as the last "complete code" response.
121
+ # You can copy and paste the rest of the functions from the previous version,
122
+ # as they will work correctly with the new server-side session management.
123
  @app.route('/chat', methods=['POST'])
124
  def chat():
 
125
  if not model:
126
  return jsonify({"error": "Gemini API is not configured. Please check your API key."}), 500
127
 
 
137
  session['chat_history'].append({"role": "user", "parts": [user_message]})
138
  session.modified = True
139
 
 
140
  chat_session = model.start_chat(history=session['chat_history'])
141
 
142
  try:
 
177
 
178
  @app.route('/file_tree')
179
  def get_file_tree():
 
180
  project_id = session.get('project_id')
181
  if not project_id:
182
  return jsonify({"error": "No project in session."}), 400
 
188
 
189
  @app.route('/file_content')
190
  def get_file_content():
 
191
  project_id = session.get('project_id')
192
  file_path = request.args.get('path')
193
  if not project_id or not file_path:
 
205
 
206
  @app.route('/download')
207
  def download_project():
 
208
  project_id = session.get('project_id')
209
  if not project_id:
210
  return "No project to download.", 404
 
221
 
222
 
223
  if __name__ == '__main__':
224
+ app.run(debug=True, port=5001)