Akwbw commited on
Commit
b27d2f2
Β·
verified Β·
1 Parent(s): 93db0b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -81
app.py CHANGED
@@ -11,11 +11,11 @@ API_ENDPOINT = "https://gen.pollinations.ai/v1/chat/completions"
11
  API_KEY = "sk_qDYtDvntvqzjmp23XKVzr9lBXYwYndaR"
12
  AI_MODEL = "claude"
13
 
14
- st.set_page_config(page_title="Auto-Upgrade Builder", layout="centered")
15
- st.title("πŸ›‘οΈ AI Builder + Auto-Upgrade Engine")
16
- st.markdown("Agar project purana hua to system khud usay modernize karega.")
17
 
18
- # --- HELPER: AI API ---
19
  def ask_claude(system_prompt, user_message):
20
  headers = {
21
  "Content-Type": "application/json",
@@ -30,12 +30,12 @@ def ask_claude(system_prompt, user_message):
30
  "temperature": 0.1
31
  }
32
  try:
33
- response = requests.post(API_ENDPOINT, json=payload, headers=headers, timeout=60)
34
  if response.status_code == 200:
35
  return True, response.json()['choices'][0]['message']['content']
36
- return False, "API Error"
37
- except:
38
- return False, "Connection Error"
39
 
40
  # --- HELPER: KEYSTORE ---
41
  def generate_keystore():
@@ -49,57 +49,80 @@ def generate_keystore():
49
  ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
50
  return keystore_path
51
 
52
- # --- πŸ› οΈ THE MODERNIZER (JADOO) ---
53
- # Ye function puranay project ko zabardasti naya bana dega
54
- def force_upgrade_engine(project_root, status_box):
55
- status_box.write("πŸ”§ Project Engine bahut purana hai. Zabardasti Upgrade kar raha hun...")
56
 
57
- # 1. Force Gradle Wrapper to 8.0 (Compatible with Java 17)
58
  wrapper_props = None
59
  for root, dirs, files in os.walk(project_root):
60
  if "gradle-wrapper.properties" in files:
61
  wrapper_props = os.path.join(root, "gradle-wrapper.properties")
62
  break
63
-
64
- if wrapper_props:
65
- new_props = """distributionBase=GRADLE_USER_HOME
 
 
 
 
66
  distributionPath=wrapper/dists
67
  distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
68
  zipStoreBase=GRADLE_USER_HOME
69
  zipStorePath=wrapper/dists
70
  """
71
- with open(wrapper_props, "w") as f:
72
- f.write(new_props)
73
- status_box.write("βœ… Gradle Wrapper set to 8.0")
74
-
75
- # 2. Update Classpath in build.gradle
76
- root_gradle = None
 
 
 
 
 
 
77
  for root, dirs, files in os.walk(project_root):
78
- if "build.gradle" in files and "app" not in root: # Root level
79
- root_gradle = os.path.join(root, "build.gradle")
80
  break
81
-
82
- if root_gradle:
83
- with open(root_gradle, "r") as f: content = f.read()
84
- # Regex to replace old classpath with new one
85
- new_content = re.sub(r"classpath\s+['\"]com.android.tools.build:gradle:.*?['\"]",
86
- "classpath 'com.android.tools.build:gradle:8.0.0'", content)
 
87
 
88
- # Add google() if missing
89
- if "google()" not in new_content:
90
- new_content = new_content.replace("repositories {", "repositories {\n google()\n mavenCentral()")
91
-
92
- with open(root_gradle, "w") as f: f.write(new_content)
93
- status_box.write("βœ… Build Plugin updated to 8.0.0")
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  # --- MAIN LOGIC ---
96
  uploaded_file = st.file_uploader("Project ZIP Upload", type=["zip"])
97
 
98
  if uploaded_file:
99
- if st.button("πŸš€ Start Auto-Build"):
100
- status_box = st.status("Initializing...", expanded=True)
101
 
102
- # 1. EXTRACT
103
  if os.path.exists("project_extract"): shutil.rmtree("project_extract")
104
  os.makedirs("project_extract", exist_ok=True)
105
  with open("uploaded.zip", "wb") as f: f.write(uploaded_file.getbuffer())
@@ -116,66 +139,60 @@ if uploaded_file:
116
  st.stop()
117
 
118
  subprocess.run(["chmod", "+x", os.path.join(project_root, "gradlew")])
119
-
120
- # 2. ATTEMPT 1: NORMAL BUILD
121
- status_box.write("πŸ”¨ Attempt 1: Building with default settings...")
122
  cmd = ["./gradlew", "clean", "assembleRelease", "--no-daemon", "--stacktrace"]
123
  result = subprocess.run(cmd, cwd=project_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
124
 
125
- success = False
 
126
  if result.returncode == 0:
127
- success = True
128
  else:
129
- # 3. FAILURE DETECTED -> UPGRADE ENGINE -> ATTEMPT 2
130
- status_box.write("❌ Attempt 1 Failed. Checking if engine is old...")
 
 
 
 
131
 
132
- # Agar 'Daemon' ya 'Java' ka error hai to Modernizer chalao
133
- logs = result.stderr
134
- if "Daemon" in logs or "Java" in logs or "Minimum supported Gradle" in logs:
135
- force_upgrade_engine(project_root, status_box)
 
 
136
 
137
- status_box.write("πŸ”„ Attempt 2: Rebuilding with NEW Engine...")
138
  result = subprocess.run(cmd, cwd=project_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
139
 
140
  if result.returncode == 0:
141
- success = True
142
  else:
143
- # 4. STILL FAILING -> USE AI FOR CODE ERRORS -> ATTEMPT 3
144
- status_box.write("❌ Attempt 2 Failed. Now checking Code Errors with AI...")
145
-
146
  logs = result.stderr
147
- # Find broken file from logs
148
- match = re.search(r'(/[\w/-]+\.(java|kt|xml|gradle)):(\d+):', logs)
149
  if match:
150
  broken_file = match.group(1)
151
- # Fix path
152
  if not os.path.exists(broken_file):
153
- for r, d, f in os.walk(project_root):
154
  if os.path.basename(broken_file) in f:
155
  broken_file = os.path.join(r, os.path.basename(broken_file))
156
  break
157
-
158
  if os.path.exists(broken_file):
159
- with open(broken_file, 'r') as f: code = f.read()
160
- status_box.write(f"πŸ€– AI Fixing: {os.path.basename(broken_file)}")
161
-
162
- prompt = "Fix this compile error strictly. Return only code."
163
- msg = f"Error: {logs[-1000:]}\n\nCode:\n{code}"
164
- ok, fixed_code = ask_claude(prompt, msg)
165
-
166
  if ok:
167
- clean_code = fixed_code.replace("```java","").replace("```","").strip()
168
- with open(broken_file, 'w') as f: f.write(clean_code)
169
- status_box.write("βœ… Code Fixed. Final Retry...")
170
-
171
  result = subprocess.run(cmd, cwd=project_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
172
- if result.returncode == 0: success = True
173
 
174
- # 5. FINAL RESULT
175
- if success:
176
  status_box.update(label="βœ… Build Successful! Signing...", state="complete")
177
-
178
- # Find APK
179
  target_apk = None
180
  for root, dirs, files in os.walk(project_root):
181
  for file in files:
@@ -185,15 +202,15 @@ if uploaded_file:
185
 
186
  if target_apk:
187
  keystore = generate_keystore()
188
- signed = "Auto_Fixed_App.apk"
189
  subprocess.run(["zipalign", "-v", "-p", "4", target_apk, "aligned.apk"], stdout=subprocess.DEVNULL)
190
  subprocess.run(["apksigner", "sign", "--ks", keystore, "--ks-pass", "pass:android", "--out", signed, "aligned.apk"])
191
 
192
  with open(signed, "rb") as f:
193
- st.download_button("⬇️ Download 100% Working APK", f, file_name=signed)
194
  else:
195
- status_box.update(label="❌ Fatal Error", state="error")
196
- st.error("System could not auto-fix this project.")
197
- st.text_area("Last Logs", result.stderr[-2000:], height=300)
198
 
199
  if os.path.exists("uploaded.zip"): os.remove("uploaded.zip")
 
11
  API_KEY = "sk_qDYtDvntvqzjmp23XKVzr9lBXYwYndaR"
12
  AI_MODEL = "claude"
13
 
14
+ st.set_page_config(page_title="God Mode AI Builder", layout="centered")
15
+ st.title("⚑ God Mode AI Android Builder")
16
+ st.markdown("Ye system haar nahi maanega. Engine Upgrade + Full AI Surgery enabled.")
17
 
18
+ # --- HELPER: AI API (Robust) ---
19
  def ask_claude(system_prompt, user_message):
20
  headers = {
21
  "Content-Type": "application/json",
 
30
  "temperature": 0.1
31
  }
32
  try:
33
+ response = requests.post(API_ENDPOINT, json=payload, headers=headers, timeout=120)
34
  if response.status_code == 200:
35
  return True, response.json()['choices'][0]['message']['content']
36
+ return False, f"API Error: {response.text}"
37
+ except Exception as e:
38
+ return False, f"Connection Error: {str(e)}"
39
 
40
  # --- HELPER: KEYSTORE ---
41
  def generate_keystore():
 
49
  ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
50
  return keystore_path
51
 
52
+ # --- πŸ› οΈ STEP 1: FORCE ENGINE UPGRADE ---
53
+ def force_modernize_engine(project_root, status_box):
54
+ status_box.write("πŸ”§ Force-Updating Gradle Engine to 8.0...")
 
55
 
56
+ # 1. Wrapper Update
57
  wrapper_props = None
58
  for root, dirs, files in os.walk(project_root):
59
  if "gradle-wrapper.properties" in files:
60
  wrapper_props = os.path.join(root, "gradle-wrapper.properties")
61
  break
62
+
63
+ # Agar wrapper nahi bhi mila, tab bhi naya banao
64
+ if not wrapper_props:
65
+ os.makedirs(os.path.join(project_root, "gradle", "wrapper"), exist_ok=True)
66
+ wrapper_props = os.path.join(project_root, "gradle", "wrapper", "gradle-wrapper.properties")
67
+
68
+ new_props = """distributionBase=GRADLE_USER_HOME
69
  distributionPath=wrapper/dists
70
  distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
71
  zipStoreBase=GRADLE_USER_HOME
72
  zipStorePath=wrapper/dists
73
  """
74
+ with open(wrapper_props, "w") as f: f.write(new_props)
75
+
76
+ # 2. Permissions Fix
77
+ subprocess.run(["chmod", "+x", os.path.join(project_root, "gradlew")])
78
+
79
+ # --- 🧠 STEP 2: AI SURGERY (Build.gradle Fixer) ---
80
+ def ai_fix_build_gradle(project_root, error_log, status_box):
81
+ status_box.write("🧠 AI is performing surgery on build.gradle...")
82
+
83
+ # Find root build.gradle and app build.gradle
84
+ root_gradle = os.path.join(project_root, "build.gradle")
85
+ app_gradle = None
86
  for root, dirs, files in os.walk(project_root):
87
+ if "build.gradle" in files and "app" in root:
88
+ app_gradle = os.path.join(root, "build.gradle")
89
  break
90
+
91
+ files_to_fix = []
92
+ if os.path.exists(root_gradle): files_to_fix.append(root_gradle)
93
+ if app_gradle: files_to_fix.append(app_gradle)
94
+
95
+ for gradle_file in files_to_fix:
96
+ with open(gradle_file, 'r', errors='ignore') as f: content = f.read()
97
 
98
+ prompt = """
99
+ You are an Android Build Expert. The build failed on Java 17 + Gradle 8.
100
+ Fix the 'build.gradle' file content.
101
+
102
+ RULES:
103
+ 1. If it's Root gradle: Use 'classpath "com.android.tools.build:gradle:8.0.0"'
104
+ 2. If it's App gradle: Ensure 'namespace' is present (if missing, use package name from manifest logic or generic 'com.example.app').
105
+ 3. Remove deprecated 'jcenter()', use 'mavenCentral()' and 'google()'.
106
+ 4. Output ONLY the code.
107
+ """
108
+
109
+ user_msg = f"Error Logs:\n{error_log[-1000:]}\n\nFile Content:\n{content}"
110
+
111
+ success, new_code = ask_claude(prompt, user_msg)
112
+
113
+ if success:
114
+ clean_code = new_code.replace("```gradle", "").replace("```groovy", "").replace("```", "").strip()
115
+ with open(gradle_file, 'w') as f: f.write(clean_code)
116
+ status_box.write(f"βœ… AI Rewrote {os.path.basename(gradle_file)}")
117
 
118
  # --- MAIN LOGIC ---
119
  uploaded_file = st.file_uploader("Project ZIP Upload", type=["zip"])
120
 
121
  if uploaded_file:
122
+ if st.button("πŸš€ Start God Mode Build"):
123
+ status_box = st.status("Initializing God Mode...", expanded=True)
124
 
125
+ # EXTRACT
126
  if os.path.exists("project_extract"): shutil.rmtree("project_extract")
127
  os.makedirs("project_extract", exist_ok=True)
128
  with open("uploaded.zip", "wb") as f: f.write(uploaded_file.getbuffer())
 
139
  st.stop()
140
 
141
  subprocess.run(["chmod", "+x", os.path.join(project_root, "gradlew")])
142
+
143
+ # === ATTEMPT 1: RAW BUILD ===
144
+ status_box.write("πŸ”¨ Attempt 1: Initial Build...")
145
  cmd = ["./gradlew", "clean", "assembleRelease", "--no-daemon", "--stacktrace"]
146
  result = subprocess.run(cmd, cwd=project_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
147
 
148
+ final_success = False
149
+
150
  if result.returncode == 0:
151
+ final_success = True
152
  else:
153
+ # === ATTEMPT 2: FORCE ENGINE UPGRADE ===
154
+ status_box.write("❌ Attempt 1 Failed. Force-Upgrading Engine...")
155
+ force_modernize_engine(project_root, status_box)
156
+
157
+ status_box.write("πŸ”„ Attempt 2: Rebuilding with Gradle 8...")
158
+ result = subprocess.run(cmd, cwd=project_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
159
 
160
+ if result.returncode == 0:
161
+ final_success = True
162
+ else:
163
+ # === ATTEMPT 3: AI SURGERY (NO IF/ELSE CHECK - ALWAYS RUN) ===
164
+ status_box.write("❌ Attempt 2 Failed. Activating Claude AI Surgery...")
165
+ ai_fix_build_gradle(project_root, result.stderr, status_box)
166
 
167
+ status_box.write("πŸ”„ Attempt 3: Final Rebuild after AI Fix...")
168
  result = subprocess.run(cmd, cwd=project_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
169
 
170
  if result.returncode == 0:
171
+ final_success = True
172
  else:
173
+ # === LAST RESORT: Try to find code error ===
 
 
174
  logs = result.stderr
175
+ match = re.search(r'(/[\w/-]+\.(java|kt|xml)):(\d+):', logs)
 
176
  if match:
177
  broken_file = match.group(1)
 
178
  if not os.path.exists(broken_file):
179
+ for r, d, f in os.walk(project_root):
180
  if os.path.basename(broken_file) in f:
181
  broken_file = os.path.join(r, os.path.basename(broken_file))
182
  break
183
+
184
  if os.path.exists(broken_file):
185
+ status_box.write(f"πŸš‘ Emergency Fix on: {os.path.basename(broken_file)}")
186
+ with open(broken_file, 'r') as f: c = f.read()
187
+ ok, fix = ask_claude("Fix code error. Return ONLY code.", f"Error: {logs[-500:]}\nCode: {c}")
 
 
 
 
188
  if ok:
189
+ with open(broken_file, 'w') as f: f.write(fix.replace("```java","").replace("```","").strip())
 
 
 
190
  result = subprocess.run(cmd, cwd=project_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
191
+ if result.returncode == 0: final_success = True
192
 
193
+ # === FINISH ===
194
+ if final_success:
195
  status_box.update(label="βœ… Build Successful! Signing...", state="complete")
 
 
196
  target_apk = None
197
  for root, dirs, files in os.walk(project_root):
198
  for file in files:
 
202
 
203
  if target_apk:
204
  keystore = generate_keystore()
205
+ signed = "GodMode_App.apk"
206
  subprocess.run(["zipalign", "-v", "-p", "4", target_apk, "aligned.apk"], stdout=subprocess.DEVNULL)
207
  subprocess.run(["apksigner", "sign", "--ks", keystore, "--ks-pass", "pass:android", "--out", signed, "aligned.apk"])
208
 
209
  with open(signed, "rb") as f:
210
+ st.download_button("⬇️ Download APK", f, file_name=signed)
211
  else:
212
+ status_box.update(label="❌ Mission Failed", state="error")
213
+ st.error("Even God Mode couldn't fix this project.")
214
+ st.text_area("Final Logs", result.stderr[-2000:], height=300)
215
 
216
  if os.path.exists("uploaded.zip"): os.remove("uploaded.zip")