Update app.py
Browse files
app.py
CHANGED
@@ -10,24 +10,20 @@ from dotenv import load_dotenv
|
|
10 |
load_dotenv()
|
11 |
|
12 |
app = Flask(__name__)
|
13 |
-
|
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 |
-
|
20 |
-
#
|
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("
|
31 |
model = None
|
32 |
else:
|
33 |
genai.configure(api_key=gemini_api_key)
|
@@ -36,7 +32,7 @@ except Exception as e:
|
|
36 |
print(f"Error configuring Gemini API: {e}")
|
37 |
model = None
|
38 |
|
39 |
-
# Configure
|
40 |
UPLOAD_FOLDER = 'uploads'
|
41 |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
42 |
if not os.path.exists(UPLOAD_FOLDER):
|
@@ -44,6 +40,7 @@ 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,7 +57,8 @@ def get_project_files(project_path):
|
|
60 |
file_data[relative_path] = f"Error reading file: {e}"
|
61 |
return file_data
|
62 |
|
63 |
-
|
|
|
64 |
@app.route('/')
|
65 |
def index():
|
66 |
if 'project_id' not in session:
|
@@ -68,95 +66,142 @@ def index():
|
|
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:
|
|
|
78 |
file = request.files['project_zip']
|
79 |
-
if file.filename == '':
|
|
|
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):
|
|
|
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:
|
|
|
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():
|
|
|
|
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
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:
|
|
|
|
|
106 |
user_message = request.json.get('message')
|
107 |
-
if not user_message:
|
|
|
|
|
108 |
project_id = session.get('project_id')
|
109 |
-
if not project_id:
|
|
|
|
|
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 |
-
|
120 |
-
|
|
|
121 |
try:
|
122 |
-
|
|
|
|
|
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:
|
126 |
-
|
|
|
|
|
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:
|
132 |
-
|
|
|
|
|
|
|
133 |
return jsonify({"reply": ai_response})
|
134 |
-
except Exception as e:
|
|
|
|
|
135 |
|
136 |
@app.route('/file_tree')
|
137 |
def get_file_tree():
|
138 |
project_id = session.get('project_id')
|
139 |
-
if not project_id:
|
|
|
140 |
project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
141 |
-
if not os.path.exists(project_path):
|
|
|
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:
|
|
|
149 |
full_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id, file_path)
|
150 |
-
if not os.path.exists(full_path):
|
|
|
151 |
try:
|
152 |
-
with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
|
|
|
153 |
return jsonify({"path": file_path, "content": content})
|
154 |
-
except Exception as e:
|
|
|
|
|
155 |
|
156 |
@app.route('/download')
|
157 |
def download_project():
|
158 |
project_id = session.get('project_id')
|
159 |
-
if not project_id:
|
|
|
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,6 +213,6 @@ def download_project():
|
|
168 |
zipf.write(file_path, arcname)
|
169 |
return send_from_directory(app.config['UPLOAD_FOLDER'], zip_filename, as_attachment=True)
|
170 |
|
171 |
-
|
172 |
if __name__ == '__main__':
|
173 |
app.run(host="0.0.0.0", port=7860)
|
|
|
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 |
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 |
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 |
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 |
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 |
+
|
95 |
initial_context = "The user has uploaded a new project. Here is the file structure and content:\n\n"
|
96 |
+
for path, content in project_files.items():
|
97 |
+
initial_context += f"**File:** `{path}`\n```\n{content}\n```\n\n"
|
98 |
+
|
99 |
session['chat_history'] = [
|
100 |
{"role": "user", "parts": [initial_context]},
|
101 |
{"role": "model", "parts": ["I have analyzed the project. I am ready to help. How can I assist you with your code?"]}
|
102 |
]
|
103 |
+
session.modified = True
|
104 |
+
|
105 |
frontend_chat_history = [
|
106 |
{"role": "user", "content": initial_context},
|
107 |
{"role": "assistant", "content": "I have analyzed the project. I am ready to help. How can I assist you with your code?"}
|
108 |
]
|
109 |
+
|
110 |
+
return jsonify({
|
111 |
+
"message": "Project uploaded and analyzed.",
|
112 |
+
"file_tree": list(project_files.keys()),
|
113 |
+
"chat_history": frontend_chat_history
|
114 |
+
})
|
115 |
return jsonify({"error": "Invalid file type. Please upload a .zip file."}), 400
|
116 |
|
117 |
@app.route('/chat', methods=['POST'])
|
118 |
def chat():
|
119 |
+
if not model:
|
120 |
+
return jsonify({"error": "Gemini API is not configured. Please check your API key."}), 500
|
121 |
+
|
122 |
user_message = request.json.get('message')
|
123 |
+
if not user_message:
|
124 |
+
return jsonify({"error": "Empty message"}), 400
|
125 |
+
|
126 |
project_id = session.get('project_id')
|
127 |
+
if not project_id:
|
128 |
+
return jsonify({"error": "Your session has expired or could not be found. Please upload your project again."}), 400
|
129 |
+
|
130 |
project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
131 |
session['chat_history'].append({"role": "user", "parts": [user_message]})
|
132 |
+
session.modified = True
|
133 |
+
|
134 |
chat_session = model.start_chat(history=session['chat_history'])
|
135 |
+
|
136 |
try:
|
137 |
response = chat_session.send_message(user_message)
|
138 |
ai_response = response.text
|
139 |
+
|
140 |
session['chat_history'].append({"role": "model", "parts": [ai_response]})
|
141 |
+
session.modified = True
|
142 |
+
|
143 |
if "```" in ai_response:
|
144 |
lines = ai_response.split('\n')
|
145 |
+
file_path_line = lines[0].strip()
|
146 |
+
if file_path_line.startswith('`') and file_path_line.endswith('`'):
|
147 |
+
file_path = file_path_line.strip('`')
|
148 |
try:
|
149 |
+
content_start = ai_response.find('```')
|
150 |
+
code_block = ai_response[content_start:]
|
151 |
+
code_content = '\n'.join(code_block.split('\n')[1:-1])
|
152 |
full_path = os.path.join(project_path, file_path)
|
153 |
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
154 |
+
with open(full_path, 'w', encoding='utf-8') as f:
|
155 |
+
f.write(code_content)
|
156 |
+
except IndexError:
|
157 |
+
pass
|
158 |
elif ai_response.strip().startswith("DELETE:"):
|
159 |
file_to_delete = ai_response.strip().split(":", 1)[1].strip()
|
160 |
full_path = os.path.join(project_path, file_to_delete)
|
161 |
if os.path.exists(full_path):
|
162 |
+
try:
|
163 |
+
os.remove(full_path)
|
164 |
+
except OSError as e:
|
165 |
+
print(f"Error deleting file {full_path}: {e}")
|
166 |
+
|
167 |
return jsonify({"reply": ai_response})
|
168 |
+
except Exception as e:
|
169 |
+
return jsonify({"error": str(e)}), 500
|
170 |
+
|
171 |
|
172 |
@app.route('/file_tree')
|
173 |
def get_file_tree():
|
174 |
project_id = session.get('project_id')
|
175 |
+
if not project_id:
|
176 |
+
return jsonify({"error": "No project in session."}), 400
|
177 |
project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
178 |
+
if not os.path.exists(project_path):
|
179 |
+
return jsonify({"file_tree": []})
|
180 |
return jsonify({"file_tree": list(get_project_files(project_path).keys())})
|
181 |
|
182 |
+
|
183 |
@app.route('/file_content')
|
184 |
def get_file_content():
|
185 |
project_id = session.get('project_id')
|
186 |
file_path = request.args.get('path')
|
187 |
+
if not project_id or not file_path:
|
188 |
+
return jsonify({"error": "Missing project or file path"}), 400
|
189 |
full_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id, file_path)
|
190 |
+
if not os.path.exists(full_path):
|
191 |
+
return jsonify({"error": "File not found"}), 404
|
192 |
try:
|
193 |
+
with open(full_path, 'r', encoding='utf-8', errors='ignore') as f:
|
194 |
+
content = f.read()
|
195 |
return jsonify({"path": file_path, "content": content})
|
196 |
+
except Exception as e:
|
197 |
+
return jsonify({"error": str(e)}), 500
|
198 |
+
|
199 |
|
200 |
@app.route('/download')
|
201 |
def download_project():
|
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)
|
|
|
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(host="0.0.0.0", port=7860)
|