Update app.py
Browse files
app.py
CHANGED
@@ -10,12 +10,17 @@ 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", '
|
14 |
|
15 |
# Configure the Gemini API client
|
16 |
try:
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
19 |
except Exception as e:
|
20 |
print(f"Error configuring Gemini API: {e}")
|
21 |
model = None
|
@@ -23,7 +28,6 @@ except Exception as e:
|
|
23 |
# Configure the upload folder
|
24 |
UPLOAD_FOLDER = 'uploads'
|
25 |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
26 |
-
|
27 |
if not os.path.exists(UPLOAD_FOLDER):
|
28 |
os.makedirs(UPLOAD_FOLDER)
|
29 |
|
@@ -34,13 +38,11 @@ def get_project_files(project_path):
|
|
34 |
file_data = {}
|
35 |
for root, _, files in os.walk(project_path):
|
36 |
for file in files:
|
37 |
-
|
38 |
-
if file == '.DS_Store':
|
39 |
-
continue
|
40 |
file_path = os.path.join(root, file)
|
41 |
relative_path = os.path.relpath(file_path, project_path)
|
42 |
try:
|
43 |
-
with open(file_path, 'r', encoding='utf-8') as f:
|
44 |
content = f.read()
|
45 |
file_data[relative_path] = content
|
46 |
except Exception as e:
|
@@ -61,7 +63,6 @@ def index():
|
|
61 |
@app.route('/upload', methods=['POST'])
|
62 |
def upload_project():
|
63 |
"""Handles the project zip file upload."""
|
64 |
-
# FIX: Ensure session is initialized to prevent KeyError
|
65 |
if 'project_id' not in session:
|
66 |
session['project_id'] = str(uuid.uuid4())
|
67 |
session['chat_history'] = []
|
@@ -86,8 +87,6 @@ def upload_project():
|
|
86 |
os.remove(zip_path)
|
87 |
|
88 |
project_files = get_project_files(project_path)
|
89 |
-
session['project_files'] = project_files
|
90 |
-
|
91 |
initial_context = "The user has uploaded a new project. Here is the file structure and content:\n\n"
|
92 |
for path, content in project_files.items():
|
93 |
initial_context += f"**File:** `{path}`\n```\n{content}\n```\n\n"
|
@@ -107,7 +106,6 @@ def upload_project():
|
|
107 |
"file_tree": list(project_files.keys()),
|
108 |
"chat_history": frontend_chat_history
|
109 |
})
|
110 |
-
|
111 |
return jsonify({"error": "Invalid file type. Please upload a .zip file."}), 400
|
112 |
|
113 |
|
@@ -115,47 +113,30 @@ def upload_project():
|
|
115 |
def chat():
|
116 |
"""Handles chat interaction with the Gemini API."""
|
117 |
if not model:
|
118 |
-
|
119 |
|
120 |
user_message = request.json.get('message')
|
121 |
if not user_message:
|
122 |
return jsonify({"error": "Empty message"}), 400
|
123 |
|
124 |
project_id = session.get('project_id')
|
125 |
-
|
|
|
126 |
|
127 |
-
|
128 |
session['chat_history'].append({"role": "user", "parts": [user_message]})
|
129 |
session.modified = True
|
130 |
|
|
|
131 |
chat_session = model.start_chat(history=session['chat_history'])
|
132 |
|
133 |
try:
|
134 |
-
|
135 |
-
1. When asked to modify a file, you MUST respond with the full file path on the first line, followed by the complete, updated code for that file inside a markdown code block. Example:
|
136 |
-
`src/app.js`
|
137 |
-
```javascript
|
138 |
-
// new updated javascript code
|
139 |
-
```
|
140 |
-
2. When asked to create a new file, respond with the new file path and its content in the same format.
|
141 |
-
3. When asked to delete a file, respond ONLY with 'DELETE: [file_path]'.
|
142 |
-
4. For general conversation, just respond naturally."""
|
143 |
-
|
144 |
-
# The history already provides context. We send the latest user message.
|
145 |
-
# The system instruction is part of the model's configuration or initial prompt.
|
146 |
-
# For simplicity here, we prepend it to guide this specific turn.
|
147 |
-
# A more advanced setup might use the system_instruction parameter in genai.configure
|
148 |
-
prompt_with_instruction = f"{system_instruction}\n\n## Project Context:\n{get_project_files(project_path)}\n\n## Conversation History:\n{session['chat_history']}\n\n## User's Latest Message:\n{user_message}"
|
149 |
-
|
150 |
-
response = chat_session.send_message(user_message) # Send only the new message
|
151 |
ai_response = response.text
|
152 |
|
153 |
-
# Add AI response to chat history
|
154 |
session['chat_history'].append({"role": "model", "parts": [ai_response]})
|
155 |
session.modified = True
|
156 |
|
157 |
-
# --- AI File Operation Logic ---
|
158 |
-
# A more robust solution might involve structured JSON output from the LLM
|
159 |
if "```" in ai_response:
|
160 |
lines = ai_response.split('\n')
|
161 |
file_path_line = lines[0].strip()
|
@@ -164,16 +145,13 @@ def chat():
|
|
164 |
try:
|
165 |
content_start = ai_response.find('```')
|
166 |
code_block = ai_response[content_start:]
|
167 |
-
# Extract language and content
|
168 |
code_content = '\n'.join(code_block.split('\n')[1:-1])
|
169 |
-
|
170 |
full_path = os.path.join(project_path, file_path)
|
171 |
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
172 |
with open(full_path, 'w', encoding='utf-8') as f:
|
173 |
f.write(code_content)
|
174 |
except IndexError:
|
175 |
-
pass
|
176 |
-
|
177 |
elif ai_response.strip().startswith("DELETE:"):
|
178 |
file_to_delete = ai_response.strip().split(":", 1)[1].strip()
|
179 |
full_path = os.path.join(project_path, file_to_delete)
|
@@ -184,7 +162,6 @@ def chat():
|
|
184 |
print(f"Error deleting file {full_path}: {e}")
|
185 |
|
186 |
return jsonify({"reply": ai_response})
|
187 |
-
|
188 |
except Exception as e:
|
189 |
return jsonify({"error": str(e)}), 500
|
190 |
|
@@ -197,9 +174,8 @@ def get_file_tree():
|
|
197 |
return jsonify({"error": "No project in session."}), 400
|
198 |
project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
199 |
if not os.path.exists(project_path):
|
200 |
-
return jsonify({"
|
201 |
-
file_tree
|
202 |
-
return jsonify({"file_tree": file_tree})
|
203 |
|
204 |
|
205 |
@app.route('/file_content')
|
@@ -209,12 +185,11 @@ def get_file_content():
|
|
209 |
file_path = request.args.get('path')
|
210 |
if not project_id or not file_path:
|
211 |
return jsonify({"error": "Missing project or file path"}), 400
|
212 |
-
|
213 |
full_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id, file_path)
|
214 |
if not os.path.exists(full_path):
|
215 |
return jsonify({"error": "File not found"}), 404
|
216 |
try:
|
217 |
-
with open(full_path, 'r', encoding='utf-8') as f:
|
218 |
content = f.read()
|
219 |
return jsonify({"path": file_path, "content": content})
|
220 |
except Exception as e:
|
@@ -227,20 +202,17 @@ def download_project():
|
|
227 |
project_id = session.get('project_id')
|
228 |
if not project_id:
|
229 |
return "No project to download.", 404
|
230 |
-
|
231 |
project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
232 |
zip_filename = f"project_{project_id}.zip"
|
233 |
zip_path = os.path.join(app.config['UPLOAD_FOLDER'], zip_filename)
|
234 |
-
|
235 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
236 |
for root, _, files in os.walk(project_path):
|
237 |
for file in files:
|
238 |
file_path = os.path.join(root, file)
|
239 |
arcname = os.path.relpath(file_path, project_path)
|
240 |
zipf.write(file_path, arcname)
|
241 |
-
|
242 |
return send_from_directory(app.config['UPLOAD_FOLDER'], zip_filename, as_attachment=True)
|
243 |
|
244 |
|
245 |
if __name__ == '__main__':
|
246 |
-
app.run(
|
|
|
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:
|
17 |
+
gemini_api_key = os.environ.get("GEMINI_API_KEY")
|
18 |
+
if not gemini_api_key:
|
19 |
+
print("GEMINI_API_KEY environment variable not found.")
|
20 |
+
model = None
|
21 |
+
else:
|
22 |
+
genai.configure(api_key=gemini_api_key)
|
23 |
+
model = genai.GenerativeModel('gemini-1.5-flash')
|
24 |
except Exception as e:
|
25 |
print(f"Error configuring Gemini API: {e}")
|
26 |
model = None
|
|
|
28 |
# Configure the upload folder
|
29 |
UPLOAD_FOLDER = 'uploads'
|
30 |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
|
|
31 |
if not os.path.exists(UPLOAD_FOLDER):
|
32 |
os.makedirs(UPLOAD_FOLDER)
|
33 |
|
|
|
38 |
file_data = {}
|
39 |
for root, _, files in os.walk(project_path):
|
40 |
for file in files:
|
41 |
+
if file in ['.DS_Store', '__MACOSX']: continue
|
|
|
|
|
42 |
file_path = os.path.join(root, file)
|
43 |
relative_path = os.path.relpath(file_path, project_path)
|
44 |
try:
|
45 |
+
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
|
46 |
content = f.read()
|
47 |
file_data[relative_path] = content
|
48 |
except Exception as e:
|
|
|
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'] = []
|
|
|
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"
|
|
|
106 |
"file_tree": list(project_files.keys()),
|
107 |
"chat_history": frontend_chat_history
|
108 |
})
|
|
|
109 |
return jsonify({"error": "Invalid file type. Please upload a .zip file."}), 400
|
110 |
|
111 |
|
|
|
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 |
|
118 |
user_message = request.json.get('message')
|
119 |
if not user_message:
|
120 |
return jsonify({"error": "Empty message"}), 400
|
121 |
|
122 |
project_id = session.get('project_id')
|
123 |
+
if not project_id:
|
124 |
+
return jsonify({"error": "Your session has expired or could not be found. Please upload your project again."}), 400
|
125 |
|
126 |
+
project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
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:
|
134 |
+
response = chat_session.send_message(user_message)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
ai_response = response.text
|
136 |
|
|
|
137 |
session['chat_history'].append({"role": "model", "parts": [ai_response]})
|
138 |
session.modified = True
|
139 |
|
|
|
|
|
140 |
if "```" in ai_response:
|
141 |
lines = ai_response.split('\n')
|
142 |
file_path_line = lines[0].strip()
|
|
|
145 |
try:
|
146 |
content_start = ai_response.find('```')
|
147 |
code_block = ai_response[content_start:]
|
|
|
148 |
code_content = '\n'.join(code_block.split('\n')[1:-1])
|
|
|
149 |
full_path = os.path.join(project_path, file_path)
|
150 |
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
151 |
with open(full_path, 'w', encoding='utf-8') as f:
|
152 |
f.write(code_content)
|
153 |
except IndexError:
|
154 |
+
pass
|
|
|
155 |
elif ai_response.strip().startswith("DELETE:"):
|
156 |
file_to_delete = ai_response.strip().split(":", 1)[1].strip()
|
157 |
full_path = os.path.join(project_path, file_to_delete)
|
|
|
162 |
print(f"Error deleting file {full_path}: {e}")
|
163 |
|
164 |
return jsonify({"reply": ai_response})
|
|
|
165 |
except Exception as e:
|
166 |
return jsonify({"error": str(e)}), 500
|
167 |
|
|
|
174 |
return jsonify({"error": "No project in session."}), 400
|
175 |
project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
176 |
if not os.path.exists(project_path):
|
177 |
+
return jsonify({"file_tree": []})
|
178 |
+
return jsonify({"file_tree": list(get_project_files(project_path).keys())})
|
|
|
179 |
|
180 |
|
181 |
@app.route('/file_content')
|
|
|
185 |
file_path = request.args.get('path')
|
186 |
if not project_id or not file_path:
|
187 |
return jsonify({"error": "Missing project or file path"}), 400
|
|
|
188 |
full_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id, file_path)
|
189 |
if not os.path.exists(full_path):
|
190 |
return jsonify({"error": "File not found"}), 404
|
191 |
try:
|
192 |
+
with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
|
193 |
content = f.read()
|
194 |
return jsonify({"path": file_path, "content": content})
|
195 |
except Exception as e:
|
|
|
202 |
project_id = session.get('project_id')
|
203 |
if not project_id:
|
204 |
return "No project to download.", 404
|
|
|
205 |
project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
206 |
zip_filename = f"project_{project_id}.zip"
|
207 |
zip_path = os.path.join(app.config['UPLOAD_FOLDER'], zip_filename)
|
|
|
208 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
209 |
for root, _, files in os.walk(project_path):
|
210 |
for file in files:
|
211 |
file_path = os.path.join(root, file)
|
212 |
arcname = os.path.relpath(file_path, project_path)
|
213 |
zipf.write(file_path, arcname)
|
|
|
214 |
return send_from_directory(app.config['UPLOAD_FOLDER'], zip_filename, as_attachment=True)
|
215 |
|
216 |
|
217 |
if __name__ == '__main__':
|
218 |
+
app.run(debug=True, port=5001)
|