Update app.py
Browse files
app.py
CHANGED
@@ -1,19 +1,19 @@
|
|
1 |
import os
|
2 |
-
import zipfile
|
3 |
import uuid
|
|
|
4 |
from flask import Flask, request, jsonify, render_template, session, send_from_directory
|
5 |
from flask_session import Session
|
6 |
from dotenv import load_dotenv
|
7 |
import google.generativeai as genai
|
8 |
|
9 |
-
# Load
|
10 |
load_dotenv()
|
11 |
|
12 |
app = Flask(__name__)
|
13 |
-
app.config[
|
14 |
-
app.config[
|
15 |
-
app.config[
|
16 |
-
app.config[
|
17 |
Session(app)
|
18 |
|
19 |
UPLOAD_FOLDER = 'uploads'
|
@@ -21,12 +21,15 @@ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
|
21 |
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
22 |
os.makedirs(app.config['SESSION_FILE_DIR'], exist_ok=True)
|
23 |
|
24 |
-
#
|
25 |
-
gemini_api_key = os.getenv("GEMINI_API_KEY")
|
26 |
model = None
|
27 |
-
|
28 |
-
|
29 |
-
|
|
|
|
|
|
|
|
|
30 |
|
31 |
def get_project_files(project_path):
|
32 |
files = {}
|
@@ -50,6 +53,10 @@ def index():
|
|
50 |
|
51 |
@app.route('/upload', methods=['POST'])
|
52 |
def upload():
|
|
|
|
|
|
|
|
|
53 |
if 'project_zip' not in request.files:
|
54 |
return jsonify({'error': 'No file uploaded'}), 400
|
55 |
file = request.files['project_zip']
|
@@ -58,6 +65,8 @@ def upload():
|
|
58 |
|
59 |
project_id = session['project_id']
|
60 |
project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
|
|
|
|
61 |
if os.path.exists(project_path):
|
62 |
for root, dirs, files in os.walk(project_path, topdown=False):
|
63 |
for f in files:
|
@@ -66,6 +75,7 @@ def upload():
|
|
66 |
os.rmdir(os.path.join(root, d))
|
67 |
os.makedirs(project_path, exist_ok=True)
|
68 |
|
|
|
69 |
zip_path = os.path.join(project_path, file.filename)
|
70 |
file.save(zip_path)
|
71 |
with zipfile.ZipFile(zip_path, 'r') as z:
|
@@ -73,14 +83,13 @@ def upload():
|
|
73 |
os.remove(zip_path)
|
74 |
|
75 |
files = get_project_files(project_path)
|
76 |
-
|
77 |
-
context = "User uploaded a project:\n"
|
78 |
for path, content in files.items():
|
79 |
-
context += f"**File:** `{path}`\n```\n{content[:2000]}\n```\n\n"
|
80 |
|
81 |
session['chat_history'] = [
|
82 |
{"role": "user", "parts": [context]},
|
83 |
-
{"role": "model", "parts": ["Project loaded.
|
84 |
]
|
85 |
session.modified = True
|
86 |
|
@@ -88,8 +97,8 @@ def upload():
|
|
88 |
"message": "Project uploaded.",
|
89 |
"file_tree": list(files.keys()),
|
90 |
"chat_history": [
|
91 |
-
{"role": "user", "content": "Project
|
92 |
-
{"role": "assistant", "content": "Project loaded.
|
93 |
]
|
94 |
})
|
95 |
|
@@ -100,6 +109,10 @@ def chat():
|
|
100 |
msg = request.json.get("message")
|
101 |
if not msg:
|
102 |
return jsonify({"error": "Empty message"}), 400
|
|
|
|
|
|
|
|
|
103 |
session['chat_history'].append({"role": "user", "parts": [msg]})
|
104 |
try:
|
105 |
chat = model.start_chat(history=session['chat_history'])
|
@@ -107,21 +120,23 @@ def chat():
|
|
107 |
session['chat_history'].append({"role": "model", "parts": [reply]})
|
108 |
return jsonify({"reply": reply})
|
109 |
except Exception as e:
|
110 |
-
return jsonify({"error": str(e)})
|
111 |
|
112 |
@app.route('/file_tree')
|
113 |
def file_tree():
|
114 |
-
|
115 |
-
if not
|
116 |
return jsonify({"file_tree": []})
|
117 |
-
path = os.path.join(app.config['UPLOAD_FOLDER'],
|
118 |
return jsonify({"file_tree": list(get_project_files(path).keys())})
|
119 |
|
120 |
@app.route('/file_content')
|
121 |
def file_content():
|
122 |
-
|
123 |
-
|
124 |
-
|
|
|
|
|
125 |
try:
|
126 |
with open(full, 'r', encoding='utf-8', errors='ignore') as f:
|
127 |
return jsonify({"content": f.read()})
|
@@ -130,17 +145,17 @@ def file_content():
|
|
130 |
|
131 |
@app.route('/download')
|
132 |
def download():
|
133 |
-
|
134 |
-
if not
|
135 |
return "No project uploaded", 404
|
136 |
-
path = os.path.join(app.config['UPLOAD_FOLDER'],
|
137 |
-
|
138 |
-
with zipfile.ZipFile(
|
139 |
for root, _, files in os.walk(path):
|
140 |
for file in files:
|
141 |
fpath = os.path.join(root, file)
|
142 |
zipf.write(fpath, os.path.relpath(fpath, path))
|
143 |
-
return send_from_directory(app.config['UPLOAD_FOLDER'], f"{
|
144 |
|
145 |
if __name__ == "__main__":
|
146 |
app.run(host='0.0.0.0', port=7860)
|
|
|
1 |
import os
|
|
|
2 |
import uuid
|
3 |
+
import zipfile
|
4 |
from flask import Flask, request, jsonify, render_template, session, send_from_directory
|
5 |
from flask_session import Session
|
6 |
from dotenv import load_dotenv
|
7 |
import google.generativeai as genai
|
8 |
|
9 |
+
# Load environment variables
|
10 |
load_dotenv()
|
11 |
|
12 |
app = Flask(__name__)
|
13 |
+
app.config['SECRET_KEY'] = os.getenv("FLASK_SECRET_KEY", "insecure-key")
|
14 |
+
app.config['SESSION_TYPE'] = 'filesystem'
|
15 |
+
app.config['SESSION_PERMANENT'] = False
|
16 |
+
app.config['SESSION_FILE_DIR'] = './flask_session'
|
17 |
Session(app)
|
18 |
|
19 |
UPLOAD_FOLDER = 'uploads'
|
|
|
21 |
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
22 |
os.makedirs(app.config['SESSION_FILE_DIR'], exist_ok=True)
|
23 |
|
24 |
+
# Gemini AI setup
|
|
|
25 |
model = None
|
26 |
+
gemini_key = os.getenv("GEMINI_API_KEY")
|
27 |
+
if gemini_key:
|
28 |
+
try:
|
29 |
+
genai.configure(api_key=gemini_key)
|
30 |
+
model = genai.GenerativeModel('gemini-2.0-flash')
|
31 |
+
except Exception as e:
|
32 |
+
print(f"Gemini setup failed: {e}")
|
33 |
|
34 |
def get_project_files(project_path):
|
35 |
files = {}
|
|
|
53 |
|
54 |
@app.route('/upload', methods=['POST'])
|
55 |
def upload():
|
56 |
+
if 'project_id' not in session:
|
57 |
+
session['project_id'] = str(uuid.uuid4())
|
58 |
+
session['chat_history'] = []
|
59 |
+
|
60 |
if 'project_zip' not in request.files:
|
61 |
return jsonify({'error': 'No file uploaded'}), 400
|
62 |
file = request.files['project_zip']
|
|
|
65 |
|
66 |
project_id = session['project_id']
|
67 |
project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
68 |
+
|
69 |
+
# Clear existing files
|
70 |
if os.path.exists(project_path):
|
71 |
for root, dirs, files in os.walk(project_path, topdown=False):
|
72 |
for f in files:
|
|
|
75 |
os.rmdir(os.path.join(root, d))
|
76 |
os.makedirs(project_path, exist_ok=True)
|
77 |
|
78 |
+
# Save and extract zip
|
79 |
zip_path = os.path.join(project_path, file.filename)
|
80 |
file.save(zip_path)
|
81 |
with zipfile.ZipFile(zip_path, 'r') as z:
|
|
|
83 |
os.remove(zip_path)
|
84 |
|
85 |
files = get_project_files(project_path)
|
86 |
+
context = "User uploaded project:\n"
|
|
|
87 |
for path, content in files.items():
|
88 |
+
context += f"**File:** `{path}`\n```\n{content[:2000]}\n```\n\n"
|
89 |
|
90 |
session['chat_history'] = [
|
91 |
{"role": "user", "parts": [context]},
|
92 |
+
{"role": "model", "parts": ["Project loaded. How can I help you?"]}
|
93 |
]
|
94 |
session.modified = True
|
95 |
|
|
|
97 |
"message": "Project uploaded.",
|
98 |
"file_tree": list(files.keys()),
|
99 |
"chat_history": [
|
100 |
+
{"role": "user", "content": "Project uploaded."},
|
101 |
+
{"role": "assistant", "content": "Project loaded. How can I help you?"}
|
102 |
]
|
103 |
})
|
104 |
|
|
|
109 |
msg = request.json.get("message")
|
110 |
if not msg:
|
111 |
return jsonify({"error": "Empty message"}), 400
|
112 |
+
|
113 |
+
if 'project_id' not in session:
|
114 |
+
session['project_id'] = str(uuid.uuid4())
|
115 |
+
session['chat_history'] = []
|
116 |
session['chat_history'].append({"role": "user", "parts": [msg]})
|
117 |
try:
|
118 |
chat = model.start_chat(history=session['chat_history'])
|
|
|
120 |
session['chat_history'].append({"role": "model", "parts": [reply]})
|
121 |
return jsonify({"reply": reply})
|
122 |
except Exception as e:
|
123 |
+
return jsonify({"error": str(e)})
|
124 |
|
125 |
@app.route('/file_tree')
|
126 |
def file_tree():
|
127 |
+
project_id = session.get('project_id')
|
128 |
+
if not project_id:
|
129 |
return jsonify({"file_tree": []})
|
130 |
+
path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
131 |
return jsonify({"file_tree": list(get_project_files(path).keys())})
|
132 |
|
133 |
@app.route('/file_content')
|
134 |
def file_content():
|
135 |
+
project_id = session.get('project_id')
|
136 |
+
path = request.args.get('path')
|
137 |
+
if not project_id or not path:
|
138 |
+
return jsonify({"error": "Missing file path"}), 400
|
139 |
+
full = os.path.join(app.config['UPLOAD_FOLDER'], project_id, path)
|
140 |
try:
|
141 |
with open(full, 'r', encoding='utf-8', errors='ignore') as f:
|
142 |
return jsonify({"content": f.read()})
|
|
|
145 |
|
146 |
@app.route('/download')
|
147 |
def download():
|
148 |
+
project_id = session.get('project_id')
|
149 |
+
if not project_id:
|
150 |
return "No project uploaded", 404
|
151 |
+
path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
|
152 |
+
zip_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{project_id}.zip")
|
153 |
+
with zipfile.ZipFile(zip_path, 'w') as zipf:
|
154 |
for root, _, files in os.walk(path):
|
155 |
for file in files:
|
156 |
fpath = os.path.join(root, file)
|
157 |
zipf.write(fpath, os.path.relpath(fpath, path))
|
158 |
+
return send_from_directory(app.config['UPLOAD_FOLDER'], f"{project_id}.zip", as_attachment=True)
|
159 |
|
160 |
if __name__ == "__main__":
|
161 |
app.run(host='0.0.0.0', port=7860)
|