Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,17 +5,19 @@ import subprocess
|
|
| 5 |
import shutil
|
| 6 |
import requests
|
| 7 |
import re
|
|
|
|
| 8 |
|
| 9 |
# --- CONFIGURATION ---
|
| 10 |
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="
|
| 15 |
-
st.title("
|
| 16 |
-
st.markdown("
|
| 17 |
|
| 18 |
-
# --- HELPER: AI API
|
| 19 |
def ask_claude(system_prompt, user_message):
|
| 20 |
headers = {
|
| 21 |
"Content-Type": "application/json",
|
|
@@ -27,10 +29,10 @@ def ask_claude(system_prompt, user_message):
|
|
| 27 |
{"role": "system", "content": system_prompt},
|
| 28 |
{"role": "user", "content": user_message}
|
| 29 |
],
|
| 30 |
-
"temperature": 0.1
|
| 31 |
}
|
| 32 |
try:
|
| 33 |
-
response = requests.post(API_ENDPOINT, json=payload, headers=headers, timeout=
|
| 34 |
if response.status_code == 200:
|
| 35 |
return True, response.json()['choices'][0]['message']['content']
|
| 36 |
return False, f"API Error: {response.text}"
|
|
@@ -49,22 +51,14 @@ def generate_keystore():
|
|
| 49 |
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 50 |
return keystore_path
|
| 51 |
|
| 52 |
-
# ---
|
| 53 |
-
def
|
| 54 |
-
status_box.write("
|
| 55 |
|
| 56 |
-
# 1. Wrapper
|
| 57 |
-
wrapper_props =
|
| 58 |
-
|
| 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
|
|
@@ -72,57 +66,100 @@ 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 |
-
#
|
| 84 |
-
root_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 |
-
|
| 89 |
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
if
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
|
|
|
| 97 |
|
| 98 |
-
|
| 99 |
-
You are an Android Build Expert. The build failed on Java 17 + Gradle 8.
|
| 100 |
-
Fix the 'build.gradle' file content.
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
| 107 |
"""
|
| 108 |
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
success,
|
| 112 |
|
| 113 |
if success:
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
# --- MAIN
|
| 119 |
uploaded_file = st.file_uploader("Project ZIP Upload", type=["zip"])
|
| 120 |
|
| 121 |
if uploaded_file:
|
| 122 |
-
if st.button("π Start
|
| 123 |
-
status_box = st.status("Initializing
|
| 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())
|
|
@@ -137,62 +174,42 @@ if uploaded_file:
|
|
| 137 |
if not project_root:
|
| 138 |
st.error("Gradlew not found.")
|
| 139 |
st.stop()
|
| 140 |
-
|
| 141 |
subprocess.run(["chmod", "+x", os.path.join(project_root, "gradlew")])
|
| 142 |
|
| 143 |
-
#
|
| 144 |
-
|
| 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 |
-
|
|
|
|
|
|
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
| 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 |
-
|
|
|
|
| 162 |
else:
|
| 163 |
-
|
| 164 |
-
status_box.write("β Attempt 2 Failed. Activating Claude AI Surgery...")
|
| 165 |
-
ai_fix_build_gradle(project_root, result.stderr, status_box)
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
| 169 |
|
| 170 |
-
if
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 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 |
-
#
|
| 194 |
-
if
|
| 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,15 +219,15 @@ if uploaded_file:
|
|
| 202 |
|
| 203 |
if target_apk:
|
| 204 |
keystore = generate_keystore()
|
| 205 |
-
signed = "
|
| 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("
|
| 214 |
-
st.text_area("
|
| 215 |
|
| 216 |
if os.path.exists("uploaded.zip"): os.remove("uploaded.zip")
|
|
|
|
| 5 |
import shutil
|
| 6 |
import requests
|
| 7 |
import re
|
| 8 |
+
import time
|
| 9 |
|
| 10 |
# --- CONFIGURATION ---
|
| 11 |
API_ENDPOINT = "https://gen.pollinations.ai/v1/chat/completions"
|
| 12 |
API_KEY = "sk_qDYtDvntvqzjmp23XKVzr9lBXYwYndaR"
|
| 13 |
AI_MODEL = "claude"
|
| 14 |
+
MAX_RETRIES = 10 # AI 10 baar koshish karega haar manne se pehle
|
| 15 |
|
| 16 |
+
st.set_page_config(page_title="AI Terminator Builder", layout="centered")
|
| 17 |
+
st.title("π€ AI Terminator Builder")
|
| 18 |
+
st.markdown("This AI will **Hunt & Fix** errors recursively until the APK is built.")
|
| 19 |
|
| 20 |
+
# --- HELPER: AI API ---
|
| 21 |
def ask_claude(system_prompt, user_message):
|
| 22 |
headers = {
|
| 23 |
"Content-Type": "application/json",
|
|
|
|
| 29 |
{"role": "system", "content": system_prompt},
|
| 30 |
{"role": "user", "content": user_message}
|
| 31 |
],
|
| 32 |
+
"temperature": 0.1 # High precision
|
| 33 |
}
|
| 34 |
try:
|
| 35 |
+
response = requests.post(API_ENDPOINT, json=payload, headers=headers, timeout=60)
|
| 36 |
if response.status_code == 200:
|
| 37 |
return True, response.json()['choices'][0]['message']['content']
|
| 38 |
return False, f"API Error: {response.text}"
|
|
|
|
| 51 |
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 52 |
return keystore_path
|
| 53 |
|
| 54 |
+
# --- STEP 1: FORCE UPGRADE (Base Setup) ---
|
| 55 |
+
def initial_modernization(project_root, status_box):
|
| 56 |
+
status_box.write("π οΈ AI is modernizing project engine first...")
|
| 57 |
|
| 58 |
+
# 1. Gradle Wrapper Upgrade to 8.0
|
| 59 |
+
wrapper_props = os.path.join(project_root, "gradle", "wrapper", "gradle-wrapper.properties")
|
| 60 |
+
os.makedirs(os.path.dirname(wrapper_props), exist_ok=True)
|
|
|
|
|
|
|
|
|
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
new_props = """distributionBase=GRADLE_USER_HOME
|
| 63 |
distributionPath=wrapper/dists
|
| 64 |
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
|
|
|
|
| 66 |
zipStorePath=wrapper/dists
|
| 67 |
"""
|
| 68 |
with open(wrapper_props, "w") as f: f.write(new_props)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
# 2. Root Build.gradle Fix
|
| 71 |
+
root_gradle = None
|
|
|
|
| 72 |
for root, dirs, files in os.walk(project_root):
|
| 73 |
+
if "build.gradle" in files and "app" not in root:
|
| 74 |
+
root_gradle = os.path.join(root, "build.gradle")
|
| 75 |
break
|
| 76 |
+
|
| 77 |
+
if root_gradle:
|
| 78 |
+
with open(root_gradle, 'r') as f: content = f.read()
|
| 79 |
+
# AI se kaho dependencies update kare
|
| 80 |
+
p = "Update 'classpath' dependencies to be compatible with Gradle 8. Use 'com.android.tools.build:gradle:8.0.0'. Output full code."
|
| 81 |
+
ok, fix = ask_claude(p, content)
|
| 82 |
+
if ok:
|
| 83 |
+
clean = fix.replace("```gradle","").replace("```","").strip()
|
| 84 |
+
with open(root_gradle, 'w') as f: f.write(clean)
|
| 85 |
+
status_box.write("β
AI updated root build.gradle configuration.")
|
| 86 |
+
|
| 87 |
+
# --- STEP 2: THE FIXER LOOP ---
|
| 88 |
+
def analyze_and_fix_errors(project_root, error_log, status_box):
|
| 89 |
+
# Regex to find file paths in error logs (Java, Kotlin, XML, Gradle)
|
| 90 |
+
# Pattern looks for: /path/to/file.ext:line_number: error
|
| 91 |
+
match = re.search(r'(/[\w/-]+\.(java|kt|xml|gradle))', error_log)
|
| 92 |
+
|
| 93 |
+
target_file = None
|
| 94 |
+
|
| 95 |
+
if match:
|
| 96 |
+
extracted_path = match.group(1)
|
| 97 |
+
# Verify path exists (Handle relative/absolute mismatch)
|
| 98 |
+
if os.path.exists(extracted_path):
|
| 99 |
+
target_file = extracted_path
|
| 100 |
+
else:
|
| 101 |
+
# Try to find by filename
|
| 102 |
+
filename = os.path.basename(extracted_path)
|
| 103 |
+
for root, dirs, files in os.walk(project_root):
|
| 104 |
+
if filename in files:
|
| 105 |
+
target_file = os.path.join(root, filename)
|
| 106 |
+
break
|
| 107 |
|
| 108 |
+
# Agar Logs se file nahi mili, to fallback 'build.gradle' (App Level) par jao
|
| 109 |
+
if not target_file:
|
| 110 |
+
for root, dirs, files in os.walk(project_root):
|
| 111 |
+
if "build.gradle" in files and "app" in root:
|
| 112 |
+
target_file = os.path.join(root, "build.gradle")
|
| 113 |
+
break
|
| 114 |
|
| 115 |
+
if target_file:
|
| 116 |
+
file_name = os.path.basename(target_file)
|
| 117 |
+
status_box.write(f"π§ AI identified issue in: **{file_name}**")
|
| 118 |
|
| 119 |
+
with open(target_file, 'r', errors='ignore') as f: current_code = f.read()
|
|
|
|
|
|
|
| 120 |
|
| 121 |
+
system_prompt = """
|
| 122 |
+
You are an elite Android debugger.
|
| 123 |
+
Analyze the Error Log and the File Content.
|
| 124 |
+
Fix the code to resolve the build error.
|
| 125 |
+
Ensure Java 17 / Gradle 8 compatibility.
|
| 126 |
+
RETURN ONLY THE CORRECTED CODE. NO EXPLANATION.
|
| 127 |
"""
|
| 128 |
|
| 129 |
+
user_message = f"""
|
| 130 |
+
ERROR LOG:
|
| 131 |
+
{error_log[-2000:]}
|
| 132 |
+
|
| 133 |
+
FILE CONTENT ({file_name}):
|
| 134 |
+
{current_code}
|
| 135 |
+
"""
|
| 136 |
|
| 137 |
+
success, ai_fix = ask_claude(system_prompt, user_message)
|
| 138 |
|
| 139 |
if success:
|
| 140 |
+
# Clean response
|
| 141 |
+
cleaned_code = ai_fix.replace("```java", "").replace("```kotlin", "").replace("```xml", "").replace("```gradle", "").replace("```", "").strip()
|
| 142 |
+
|
| 143 |
+
with open(target_file, 'w', encoding='utf-8') as f:
|
| 144 |
+
f.write(cleaned_code)
|
| 145 |
+
|
| 146 |
+
status_box.write(f"π€ **AI Message:** I have corrected `{file_name}` to fix the reported error.")
|
| 147 |
+
return True
|
| 148 |
+
else:
|
| 149 |
+
status_box.error("AI API Failed to respond.")
|
| 150 |
+
return False
|
| 151 |
+
else:
|
| 152 |
+
status_box.warning("Could not identify specific broken file from logs. Trying generic fix...")
|
| 153 |
+
return False
|
| 154 |
|
| 155 |
+
# --- MAIN UI ---
|
| 156 |
uploaded_file = st.file_uploader("Project ZIP Upload", type=["zip"])
|
| 157 |
|
| 158 |
if uploaded_file:
|
| 159 |
+
if st.button("π Start Terminator Build"):
|
| 160 |
+
status_box = st.status("Initializing System...", expanded=True)
|
| 161 |
|
| 162 |
+
# 1. EXTRACT
|
| 163 |
if os.path.exists("project_extract"): shutil.rmtree("project_extract")
|
| 164 |
os.makedirs("project_extract", exist_ok=True)
|
| 165 |
with open("uploaded.zip", "wb") as f: f.write(uploaded_file.getbuffer())
|
|
|
|
| 174 |
if not project_root:
|
| 175 |
st.error("Gradlew not found.")
|
| 176 |
st.stop()
|
| 177 |
+
|
| 178 |
subprocess.run(["chmod", "+x", os.path.join(project_root, "gradlew")])
|
| 179 |
|
| 180 |
+
# 2. PRE-BUILD MODERNIZATION
|
| 181 |
+
initial_modernization(project_root, status_box)
|
|
|
|
|
|
|
| 182 |
|
| 183 |
+
# 3. THE LOOP (MAX RETRIES)
|
| 184 |
+
build_success = False
|
| 185 |
+
cmd = ["./gradlew", "assembleRelease", "--no-daemon", "--stacktrace"]
|
| 186 |
|
| 187 |
+
for attempt in range(1, MAX_RETRIES + 1):
|
| 188 |
+
status_box.write(f"π **Build Attempt {attempt}/{MAX_RETRIES}** is running...")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
|
|
|
|
| 190 |
result = subprocess.run(cmd, cwd=project_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 191 |
|
| 192 |
if result.returncode == 0:
|
| 193 |
+
build_success = True
|
| 194 |
+
break # Loop khatam, kaam ho gaya
|
| 195 |
else:
|
| 196 |
+
status_box.write(f"β Build Failed (Attempt {attempt}). AI is analyzing logs...")
|
|
|
|
|
|
|
| 197 |
|
| 198 |
+
# AI FIXING LOGIC
|
| 199 |
+
fixed = analyze_and_fix_errors(project_root, result.stderr, status_box)
|
| 200 |
|
| 201 |
+
if not fixed:
|
| 202 |
+
# Agar AI file nahi dhoond paya, to shayad "clean" ki zaroorat hai
|
| 203 |
+
subprocess.run(["./gradlew", "clean"], cwd=project_root)
|
| 204 |
+
status_box.write("π§Ή AI cleaned the project cache.")
|
| 205 |
+
|
| 206 |
+
# Thora saans lene do system ko
|
| 207 |
+
time.sleep(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
+
# 4. FINAL OUTCOME
|
| 210 |
+
if build_success:
|
| 211 |
+
status_box.update(label="β
Build Successful! Signing APK...", state="complete")
|
| 212 |
+
|
| 213 |
target_apk = None
|
| 214 |
for root, dirs, files in os.walk(project_root):
|
| 215 |
for file in files:
|
|
|
|
| 219 |
|
| 220 |
if target_apk:
|
| 221 |
keystore = generate_keystore()
|
| 222 |
+
signed = "AI_Terminator_App.apk"
|
| 223 |
subprocess.run(["zipalign", "-v", "-p", "4", target_apk, "aligned.apk"], stdout=subprocess.DEVNULL)
|
| 224 |
subprocess.run(["apksigner", "sign", "--ks", keystore, "--ks-pass", "pass:android", "--out", signed, "aligned.apk"])
|
| 225 |
|
| 226 |
with open(signed, "rb") as f:
|
| 227 |
+
st.download_button("β¬οΈ Download Final APK", f, file_name=signed)
|
| 228 |
else:
|
| 229 |
status_box.update(label="β Mission Failed", state="error")
|
| 230 |
+
st.error(f"AI tried {MAX_RETRIES} times but could not fix all errors.")
|
| 231 |
+
st.text_area("Last Error Log", result.stderr[-2000:], height=300)
|
| 232 |
|
| 233 |
if os.path.exists("uploaded.zip"): os.remove("uploaded.zip")
|