Athspi commited on
Commit
001d634
·
verified ·
1 Parent(s): 0827ef9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -89
app.py CHANGED
@@ -2,7 +2,7 @@ import os
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
 
@@ -10,20 +10,24 @@ from dotenv import load_dotenv
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:
24
  gemini_api_key = os.environ.get("GEMINI_API_KEY")
25
  if not gemini_api_key:
26
- print("GEMINI_API_KEY environment variable not found.")
27
  model = None
28
  else:
29
  genai.configure(api_key=gemini_api_key)
@@ -32,7 +36,7 @@ except Exception as e:
32
  print(f"Error configuring Gemini API: {e}")
33
  model = None
34
 
35
- # Configure the upload folder
36
  UPLOAD_FOLDER = 'uploads'
37
  app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
38
  if not os.path.exists(UPLOAD_FOLDER):
@@ -40,7 +44,6 @@ if not os.path.exists(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 = {}
@@ -57,8 +60,7 @@ def get_project_files(project_path):
57
  file_data[relative_path] = f"Error reading file: {e}"
58
  return file_data
59
 
60
-
61
- # --- Flask Routes ---
62
  @app.route('/')
63
  def index():
64
  if 'project_id' not in session:
@@ -66,148 +68,95 @@ def index():
66
  session['chat_history'] = []
67
  return render_template('index.html')
68
 
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'] = []
75
 
76
- if 'project_zip' not in request.files:
77
- return jsonify({"error": "No file part"}), 400
78
  file = request.files['project_zip']
79
- if file.filename == '':
80
- return jsonify({"error": "No selected file"}), 400
81
 
82
  if file and file.filename.endswith('.zip'):
83
  project_id = session['project_id']
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"
100
-
101
  session['chat_history'] = [
102
  {"role": "user", "parts": [initial_context]},
103
  {"role": "model", "parts": ["I have analyzed the project. I am ready to help. How can I assist you with your code?"]}
104
  ]
105
-
106
  frontend_chat_history = [
107
  {"role": "user", "content": initial_context},
108
  {"role": "assistant", "content": "I have analyzed the project. I am ready to help. How can I assist you with your code?"}
109
  ]
110
-
111
- return jsonify({
112
- "message": "Project uploaded and analyzed.",
113
- "file_tree": list(project_files.keys()),
114
- "chat_history": frontend_chat_history
115
- })
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
-
128
  user_message = request.json.get('message')
129
- if not user_message:
130
- return jsonify({"error": "Empty message"}), 400
131
-
132
  project_id = session.get('project_id')
133
- if not project_id:
134
- return jsonify({"error": "Your session has expired or could not be found. Please upload your project again."}), 400
135
-
136
  project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
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:
143
  response = chat_session.send_message(user_message)
144
  ai_response = response.text
145
-
146
  session['chat_history'].append({"role": "model", "parts": [ai_response]})
147
- session.modified = True
148
-
149
  if "```" in ai_response:
150
  lines = ai_response.split('\n')
151
- file_path_line = lines[0].strip()
152
- if file_path_line.startswith('`') and file_path_line.endswith('`'):
153
- file_path = file_path_line.strip('`')
154
  try:
155
- content_start = ai_response.find('```')
156
- code_block = ai_response[content_start:]
157
- code_content = '\n'.join(code_block.split('\n')[1:-1])
158
  full_path = os.path.join(project_path, file_path)
159
  os.makedirs(os.path.dirname(full_path), exist_ok=True)
160
- with open(full_path, 'w', encoding='utf-8') as f:
161
- f.write(code_content)
162
- except IndexError:
163
- pass
164
  elif ai_response.strip().startswith("DELETE:"):
165
  file_to_delete = ai_response.strip().split(":", 1)[1].strip()
166
  full_path = os.path.join(project_path, file_to_delete)
167
  if os.path.exists(full_path):
168
- try:
169
- os.remove(full_path)
170
- except OSError as e:
171
- print(f"Error deleting file {full_path}: {e}")
172
-
173
  return jsonify({"reply": ai_response})
174
- except Exception as e:
175
- return jsonify({"error": str(e)}), 500
176
-
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
183
  project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
184
- if not os.path.exists(project_path):
185
- return jsonify({"file_tree": []})
186
  return jsonify({"file_tree": list(get_project_files(project_path).keys())})
187
 
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:
194
- return jsonify({"error": "Missing project or file path"}), 400
195
  full_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id, file_path)
196
- if not os.path.exists(full_path):
197
- return jsonify({"error": "File not found"}), 404
198
  try:
199
- with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
200
- content = f.read()
201
  return jsonify({"path": file_path, "content": content})
202
- except Exception as e:
203
- return jsonify({"error": str(e)}), 500
204
-
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
211
  project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
212
  zip_filename = f"project_{project_id}.zip"
213
  zip_path = os.path.join(app.config['UPLOAD_FOLDER'], zip_filename)
@@ -219,6 +168,6 @@ def download_project():
219
  zipf.write(file_path, arcname)
220
  return send_from_directory(app.config['UPLOAD_FOLDER'], zip_filename, as_attachment=True)
221
 
222
-
223
  if __name__ == '__main__':
224
- 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, send_from_directory
6
  from flask_session import Session # Import the extension
7
  from dotenv import load_dotenv
8
 
 
10
  load_dotenv()
11
 
12
  app = Flask(__name__)
13
+ # IMPORTANT: The secret key will be set via Hugging Face secrets, not the .env file
14
+ app.config["SECRET_KEY"] = os.environ.get("FLASK_SECRET_KEY", 'a-strong-default-secret-key')
15
 
16
  # --- SERVER-SIDE SESSION CONFIGURATION ---
17
  app.config["SESSION_PERMANENT"] = False
18
+ app.config["SESSION_TYPE"] = "filesystem"
19
+ # On Hugging Face, the path must be persistent across reloads if possible
20
+ # A temporary directory is fine for this stateless app
21
+ app.config['SESSION_FILE_DIR'] = './flask_session'
22
+ Session(app)
23
  # --- END OF SESSION CONFIGURATION ---
24
 
25
  # Configure the Gemini API client
26
+ # The API key will be set via Hugging Face secrets
27
  try:
28
  gemini_api_key = os.environ.get("GEMINI_API_KEY")
29
  if not gemini_api_key:
30
+ print("Warning: GEMINI_API_KEY not found. The AI will not function.")
31
  model = None
32
  else:
33
  genai.configure(api_key=gemini_api_key)
 
36
  print(f"Error configuring Gemini API: {e}")
37
  model = None
38
 
39
+ # Configure folders
40
  UPLOAD_FOLDER = 'uploads'
41
  app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
42
  if not os.path.exists(UPLOAD_FOLDER):
 
44
  if not os.path.exists('./flask_session'):
45
  os.makedirs('./flask_session')
46
 
 
47
  # --- Helper Functions (No Changes) ---
48
  def get_project_files(project_path):
49
  file_data = {}
 
60
  file_data[relative_path] = f"Error reading file: {e}"
61
  return file_data
62
 
63
+ # --- Flask Routes (No Changes from previous final version) ---
 
64
  @app.route('/')
65
  def index():
66
  if 'project_id' not in session:
 
68
  session['chat_history'] = []
69
  return render_template('index.html')
70
 
 
71
  @app.route('/upload', methods=['POST'])
72
  def upload_project():
73
  if 'project_id' not in session:
74
  session['project_id'] = str(uuid.uuid4())
75
  session['chat_history'] = []
76
 
77
+ if 'project_zip' not in request.files: return jsonify({"error": "No file part"}), 400
 
78
  file = request.files['project_zip']
79
+ if file.filename == '': return jsonify({"error": "No selected file"}), 400
 
80
 
81
  if file and file.filename.endswith('.zip'):
82
  project_id = session['project_id']
83
  project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
84
+ if not os.path.exists(project_path): os.makedirs(project_path)
 
85
  zip_path = os.path.join(project_path, file.filename)
86
  file.save(zip_path)
87
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(project_path)
 
88
  os.remove(zip_path)
 
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(): initial_context += f"**File:** `{path}`\n```\n{content}\n```\n\n"
 
 
92
  session['chat_history'] = [
93
  {"role": "user", "parts": [initial_context]},
94
  {"role": "model", "parts": ["I have analyzed the project. I am ready to help. How can I assist you with your code?"]}
95
  ]
 
96
  frontend_chat_history = [
97
  {"role": "user", "content": initial_context},
98
  {"role": "assistant", "content": "I have analyzed the project. I am ready to help. How can I assist you with your code?"}
99
  ]
100
+ return jsonify({ "message": "Project uploaded and analyzed.", "file_tree": list(project_files.keys()), "chat_history": frontend_chat_history })
 
 
 
 
 
101
  return jsonify({"error": "Invalid file type. Please upload a .zip file."}), 400
102
 
 
 
 
 
 
103
  @app.route('/chat', methods=['POST'])
104
  def chat():
105
+ if not model: return jsonify({"error": "AI model not configured. The admin needs to set the API key."}), 500
 
 
106
  user_message = request.json.get('message')
107
+ if not user_message: return jsonify({"error": "Empty message"}), 400
 
 
108
  project_id = session.get('project_id')
109
+ if not project_id: return jsonify({"error": "Your session has expired. Please upload your project again."}), 400
 
 
110
  project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
111
  session['chat_history'].append({"role": "user", "parts": [user_message]})
 
 
112
  chat_session = model.start_chat(history=session['chat_history'])
 
113
  try:
114
  response = chat_session.send_message(user_message)
115
  ai_response = response.text
 
116
  session['chat_history'].append({"role": "model", "parts": [ai_response]})
 
 
117
  if "```" in ai_response:
118
  lines = ai_response.split('\n')
119
+ if lines[0].strip().startswith('`') and lines[0].strip().endswith('`'):
120
+ file_path = lines[0].strip().strip('`')
 
121
  try:
122
+ code_content = '\n'.join(ai_response.split('```')[1].split('\n')[1:])
 
 
123
  full_path = os.path.join(project_path, file_path)
124
  os.makedirs(os.path.dirname(full_path), exist_ok=True)
125
+ with open(full_path, 'w', encoding='utf-8') as f: f.write(code_content)
126
+ except IndexError: pass
 
 
127
  elif ai_response.strip().startswith("DELETE:"):
128
  file_to_delete = ai_response.strip().split(":", 1)[1].strip()
129
  full_path = os.path.join(project_path, file_to_delete)
130
  if os.path.exists(full_path):
131
+ try: os.remove(full_path)
132
+ except OSError as e: print(f"Error deleting file {full_path}: {e}")
 
 
 
133
  return jsonify({"reply": ai_response})
134
+ except Exception as e: return jsonify({"error": str(e)}), 500
 
 
135
 
136
  @app.route('/file_tree')
137
  def get_file_tree():
138
  project_id = session.get('project_id')
139
+ if not project_id: return jsonify({"error": "No project in session."}), 400
 
140
  project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
141
+ if not os.path.exists(project_path): return jsonify({"file_tree": []})
 
142
  return jsonify({"file_tree": list(get_project_files(project_path).keys())})
143
 
 
144
  @app.route('/file_content')
145
  def get_file_content():
146
  project_id = session.get('project_id')
147
  file_path = request.args.get('path')
148
+ if not project_id or not file_path: return jsonify({"error": "Missing project/file path"}), 400
 
149
  full_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id, file_path)
150
+ if not os.path.exists(full_path): return jsonify({"error": "File not found"}), 404
 
151
  try:
152
+ with open(full_path, 'r', encoding='utf-8', errors='ignore') as f: content = f.read()
 
153
  return jsonify({"path": file_path, "content": content})
154
+ except Exception as e: return jsonify({"error": str(e)}), 500
 
 
155
 
156
  @app.route('/download')
157
  def download_project():
158
  project_id = session.get('project_id')
159
+ if not project_id: return "No project to download.", 404
 
160
  project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
161
  zip_filename = f"project_{project_id}.zip"
162
  zip_path = os.path.join(app.config['UPLOAD_FOLDER'], zip_filename)
 
168
  zipf.write(file_path, arcname)
169
  return send_from_directory(app.config['UPLOAD_FOLDER'], zip_filename, as_attachment=True)
170
 
171
+ # The following is not needed for Hugging Face deployment but good for local testing
172
  if __name__ == '__main__':
173
+ app.run(debug=True, port=5001)