Athspi commited on
Commit
39138c7
·
verified ·
1 Parent(s): 0c8e549

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -14
app.py CHANGED
@@ -9,6 +9,7 @@ import google.generativeai as genai
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'
@@ -16,6 +17,7 @@ app.config['SESSION_PERMANENT'] = False
16
  app.config['SESSION_FILE_DIR'] = './flask_session'
17
  Session(app)
18
 
 
19
  UPLOAD_FOLDER = 'uploads'
20
  app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
21
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
@@ -27,7 +29,7 @@ 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
 
@@ -63,42 +65,49 @@ def upload():
63
  if not file.filename.endswith('.zip'):
64
  return jsonify({'error': 'Only .zip supported'}), 400
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:
73
- os.remove(os.path.join(root, f))
74
- for d in dirs:
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:
82
  z.extractall(project_path)
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
 
96
  return jsonify({
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
 
@@ -113,6 +122,7 @@ def chat():
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'])
 
9
  # Load environment variables
10
  load_dotenv()
11
 
12
+ # Flask app setup
13
  app = Flask(__name__)
14
  app.config['SECRET_KEY'] = os.getenv("FLASK_SECRET_KEY", "insecure-key")
15
  app.config['SESSION_TYPE'] = 'filesystem'
 
17
  app.config['SESSION_FILE_DIR'] = './flask_session'
18
  Session(app)
19
 
20
+ # Folder setup
21
  UPLOAD_FOLDER = 'uploads'
22
  app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
23
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
 
29
  if gemini_key:
30
  try:
31
  genai.configure(api_key=gemini_key)
32
+ model = genai.GenerativeModel('gemini-2.0-pro')
33
  except Exception as e:
34
  print(f"Gemini setup failed: {e}")
35
 
 
65
  if not file.filename.endswith('.zip'):
66
  return jsonify({'error': 'Only .zip supported'}), 400
67
 
68
+ # Extract project
69
  project_id = session['project_id']
70
  project_path = os.path.join(app.config['UPLOAD_FOLDER'], project_id)
 
 
71
  if os.path.exists(project_path):
72
  for root, dirs, files in os.walk(project_path, topdown=False):
73
+ for f in files: os.remove(os.path.join(root, f))
74
+ for d in dirs: os.rmdir(os.path.join(root, d))
 
 
75
  os.makedirs(project_path, exist_ok=True)
76
 
 
77
  zip_path = os.path.join(project_path, file.filename)
78
  file.save(zip_path)
79
  with zipfile.ZipFile(zip_path, 'r') as z:
80
  z.extractall(project_path)
81
  os.remove(zip_path)
82
 
83
+ # Read and prepare context
84
  files = get_project_files(project_path)
85
+ prompt = "**Analyze this project and give suggestions for improvements, refactoring, or bugs.**\n\n"
86
  for path, content in files.items():
87
+ prompt += f"File: `{path}`\n```\n{content[:1500]}\n```\n\n"
88
 
89
+ # Ask Gemini
90
+ try:
91
+ ai_response = "Gemini model is not configured."
92
+ if model:
93
+ reply = model.generate_content(prompt)
94
+ ai_response = reply.text
95
+ except Exception as e:
96
+ ai_response = f"Error talking to Gemini: {e}"
97
+
98
+ # Save chat history
99
  session['chat_history'] = [
100
+ {"role": "user", "parts": [prompt]},
101
+ {"role": "model", "parts": [ai_response]}
102
  ]
103
  session.modified = True
104
 
105
  return jsonify({
106
+ "message": "Project uploaded and analyzed by Gemini.",
107
  "file_tree": list(files.keys()),
108
  "chat_history": [
109
  {"role": "user", "content": "Project uploaded."},
110
+ {"role": "assistant", "content": ai_response}
111
  ]
112
  })
113
 
 
122
  if 'project_id' not in session:
123
  session['project_id'] = str(uuid.uuid4())
124
  session['chat_history'] = []
125
+
126
  session['chat_history'].append({"role": "user", "parts": [msg]})
127
  try:
128
  chat = model.start_chat(history=session['chat_history'])