Natural-language AI tool that analyzes APKs and generates intelligent patches from plain-English descriptions
β¨ Features β’ β‘ Quick start β’ π§° Usage β’ π§© Architecture β’ π Roadmap β’ π€ Contributing
Power users and indie Android devs waste hours manually editing Smali to customize apps or remove bloat. Existing patchers are opaque and lack explanation. APK Morph fills the gap with a clean local-LLM interface that translates plain-English intent into precise, auditable changes while keeping everything offline.
- Natural-language requests like βdisable all analyticsβ are turned into minimal, targeted Smali/XML edits
- Every change ships with a plain-English rationale, confidence score, and before/after diff
- Fully local: no data leaves your machine; works with any Ollama model and optional GPU
- One-click rebuild, zipalign, and signing (debug or custom keystore) produces a ready-to-install APK
- Supports popular local models (Gemma 2, Phi 3, Code Llama) with automatic download on first use
- Extensible plugin API lets you register custom patch types (e.g. theme injectors, permission managers)
- Export any patch as a reusable Python script or JSON template for versioning, sharing, or CI
- Direct ADB push, install (-r) and launch on a connected Android device or emulator with
--install --launch - Automatic rollback on rebuild failure ensures failed patches never leave the decompiled tree in an inconsistent state
- Optimized decompilation cache (reuses valid output when APK is unchanged) and parallel Smali parsing for large APKs (>50 MB)
- Curated patch template gallery with one-click import for popular customizations (remove ads, disable tracking, force dark theme, etc.)
Upload any APK for automatic decompilation via Apktool and Androguard metadata extraction |
Type requests like βdisable all analyticsβ and the LLM builds a targeted modification plan |
Local Ollama model maps English intent to specific methods, classes, resource IDs and strings |
Generates minimal Smali edits, XML tweaks, resource string updates (updates resources.arsc on rebuild) while preserving signatures |
Interactive side-by-side Smali diff viewer with hover explanations and plain-English rationale for every inserted or removed instruction |
Rebuilds, zipaligns and signs the new APK using test or user-provided keys |
Streamlit UI shows component tree, patch history, color-coded confidence scores, and a feedback form that refines the LLM prompt on the fly for iterative improvement |
No data leaves your machine; works with llama3.2, Gemma 2, Phi 3, Code Llama (auto-download) and optional GPU acceleration |
Register custom patch types (theme injectors, permission managers, etc.) via a simple Python decorator; LLM prompt auto-detects them |
Direct ADB push, install and launch on a connected device/emulator after patching (requires Android SDK platform-tools on PATH) |
Automatic backup + rollback of the decompiled tree when a rebuild fails, keeping source pristine |
Browse and import high-quality, pre-tested patch templates (ads removal, privacy, theming) with one click from CLI or UI |
Requirements
- Python β₯ 3.10
- Ollama running (APK Morph will automatically download Gemma 2, Phi 3, Code Llama and other supported models on first use)
- Apktool, zipalign and apksigner on your PATH (Android SDK build-tools)
- Java runtime
- adb on PATH (Android SDK platform-tools) for
--install/--launch - Frida + frida-server on device/emulator (optional β enables runtime observation; install with
pip install -e ".[frida]")
pip install -e .
apkmorph uiFor runtime-aware patches install the optional extra:
pip install -e ".[frida]"The CLI entry point apkmorph is automatically installed from pyproject.toml.
# 1. Analyze an APK
apkmorph analyze sample.apk -o report.md
# 2. Generate a patch plan from natural language (uses optional Frida runtime data)
apkmorph patch "disable all analytics, remove ads and change app name" sample.apk --model gemma2
# 3. Apply the plan, install on device and launch
apkmorph patch "disable all analytics, remove ads and change app name" sample.apk --model gemma2 --apply --install --launch
# 4. Batch-apply the same natural-language patch to many APKs
apkmorph batch "disable all analytics and remove ads" *.apk --output-dir ./patched_batch --model phi3
# 5. Export the plan for reuse (Python script or JSON template)
apkmorph export plan_abc123 --format python --output remove_ads_patch.py
# 6. Browse and import from the curated gallery (new)
apkmorph gallery
apkmorph gallery --import remove_ads --apk sample.apk --applyThe resulting patched_*.apk is ready to install. All commands are defined in src/apkmorph/cli.py.
CLI workflow
apkmorph analyze myapp.apk
apkmorph patch "remove splash screen, disable crash reporting and empty ad strings" myapp.apk --model phi3 --apply --install --launch
apkmorph explain plan_abc123
apkmorph batch "disable analytics and remove ads" app1.apk app2.apk --output-dir ./patched --no-observe
apkmorph export plan_abc123 --format pythonCurated Patch Template Gallery (new)
A growing collection of community-vetted, high-success templates. Import with one click β the template supplies an optimized prompt, the LLM tailors the plan to your specific APK, and you get rationale + confidence scores.
# List all curated templates
apkmorph gallery
# One-click import + apply
apkmorph gallery --import remove_ads --apk mygame.apk --apply --install
# Or combine with natural language for refinement
apkmorph patch "remove ads" mygame.apk --applyTemplates currently include:
remove_adsβ removes AdMob/Unity ads, replaces containers with a thank-you messagedisable_analyticsβ no-ops Firebase, Adjust, AppsFlyer, crash reportingdark_themeβ forces night mode and updates styles.xmlremove_splashβ eliminates launch screen for instant startchange_nameβ renames the app (icon swap supported via resources)add_permissionsβ adds common permissions via natural language (new)
The same gallery powers the Streamlit UI (sidebar cards with βImportβ buttons).
Exporting patches for reuse
Any generated PatchPlan can be exported as a self-contained Python script or a JSON template. The Python script embeds the exact modifications so it can be run later (or shared) without re-querying the LLM and works on similar APKs.
apkmorph export plan_7f3a9c --format python --output mypatch.py
apkmorph export plan_7f3a9c --format json --output template.jsonRun the exported script:
python mypatch.py path/to/app.apk
# or
python mypatch.py path/to/app.apk --output-dir ./patchedThe script decompiles the target, applies the saved modifications (Smali/XML/resources/plugins), rebuilds and signs the APK.
Launch the Streamlit dashboard
apkmorph ui --port 8501The UI (located in src/apkmorph/ui/app.py) provides file upload, a chat-style prompt box, the interactive side-by-side Smali diff viewer (with hover explanations on changed lines), color-coded confidence scoring, a feedback form that augments the LLM prompt for iterative refinement, a Curated Gallery panel with one-click import buttons, and one-click rebuild via APKBuilder.rebuild_and_sign().
Python library example (see examples/remove_ads.py)
from apkmorph.analyzer import APKAnalyzer
from apkmorph.patch_generator import PatchGenerator
from apkmorph.builder import APKBuilder
from pathlib import Path
analyzer = APKAnalyzer()
report = analyzer.decompile("game.apk")
report = analyzer.observe_runtime(report)
generator = PatchGenerator(model="gemma2")
# One-click import from curated gallery (new)
plan = generator.import_template("remove_ads", report)
print(plan.rationale)
print(f"Confidence: {plan.confidence:.2f}")
# Export for reuse / versioning
generator.export(plan, "remove_ads_patch.py", fmt="python")
generator.export(plan, "remove_ads_template.json", fmt="json")
builder = APKBuilder()
final_apk = builder.rebuild_and_sign(str(report.decompiled_dir))
print("Signed APK:", final_apk)
# Direct push to device (new)
builder.install_on_device(str(final_apk), report.package_name, report.main_activity)
print("Installed and launched on device")Custom patch plugins
Register handlers for new edit_type values. The LLM prompt automatically discovers registered types and their domain-specific prompt fragments (new) and the apply_modification path dispatches to your handler.
from apkmorph.plugins import register_custom_patch_type
from apkmorph.models import Modification
from pathlib import Path
@register_custom_patch_type(
"theme_injector",
prompt_fragment=(
"Use edit_type='theme_injector' when the request involves colors, "
"dark/light mode, or full theme overlays. Supply params such as "
"primary_color, accent_color, night_mode_enabled. This produces "
"more coherent theming changes than generic XML edits because the "
"handler can update styles.xml, drawables and manifest flags together."
)
)
def inject_theme(mod: Modification, decompiled_dir: Path) -> bool:
"""Example: update primary color in styles.xml (or inject full theme overlay)."""
color = mod.params.get("primary_color", "#3F51B5")
styles = decompiled_dir / "res" / "values" / "styles.xml"
if not styles.exists():
return False
content = styles.read_text(encoding="utf-8")
content = content.replace(
'android:colorPrimary">#000000',
f'android:colorPrimary">{color}'
)
styles.write_text(content, encoding="utf-8")
return True
# Use it
generator = PatchGenerator()
plan = generator.from_description(
"apply dark theme with primary color #FF5722",
report
)
# The plan may contain edit_type="theme_injector", params={"primary_color":"#FF5722"}
output = generator.apply_plan(plan, report)The supplied prompt_fragment is automatically injected into the LLM system prompt, giving the model richer, domain-specific guidance so it chooses the correct edit_type and supplies the right parameters more reliably. Register before calling from_description (or manually build a PatchPlan with the custom edit_type).
Batch mode
Process many APKs with the identical natural-language request. Each APK receives its own decompilation, runtime observation (optional), LLM-generated plan (tailored to its code), modification application, and signed output.
apkmorph batch "disable all analytics, remove ads and update app name" app1.apk app2.apk app3.apk \
--output-dir ./patched_batch --model phi3The command prints a rich summary table and places patched_*.apk files in the requested directory.
Natural-language manifest editing (new)
Requests like βadd INTERNET and READ_EXTERNAL_STORAGE permissions, register a BootCompleted receiver, remove CAMERA permissionβ are now understood. The LLM produces edit_type="manifest" modifications that SmaliEditor applies directly to AndroidManifest.xml using precise XML updates. Current manifest components are included in the LLM context for accurate suggestions.
Advanced: custom keystore and simulation
apkmorph patch "remove tracking and change strings" app.apk --apply --install --launch --model codellama
apkmorph apply --plan-id plan_7f3a9c --install --launchplan = generator.from_description("strip analytics and update resource strings", report)
simulation = generator.simulate_apply(plan, report.decompiled_dir)
print(simulation["applied"])
builder = APKBuilder()
builder.align_and_sign("unsigned.apk", keystore="release.jks")| Option | Default | Description |
|---|---|---|
llm.default_model |
llama3.2 |
Ollama model used by LLMClient; aliases gemma2/phi3/codellama also supported |
llm.auto_download |
true |
Automatically download supported models (Gemma 2, Phi 3, Code Llama) if missing |
llm.temperature |
0.15 |
Controls determinism of patch generation |
tools.apktool |
(PATH) | Full path to apktool binary |
signing.use_debug |
true |
Use ~/.android/debug.keystore when no keystore is supplied |
paths.working_dir |
decompiled |
Directory for APKAnalyzer.decompile() output |
paths.build_dir |
builds |
Intermediate artifacts for APKBuilder |
ui.port |
8501 |
Streamlit server port (passed to apkmorph ui --port) |
analysis.max_strings |
250 |
Limit passed to AnalysisReport.strings for LLM context |
frida.duration |
10 |
Observation window in seconds for Frida hooks |
frida.auto_observe |
true |
Whether from_description automatically enriches reports with runtime data |
gallery.enabled |
true |
Enable the curated template gallery in CLI and UI |
gallery.show_confidence |
true |
Display template confidence scores in gallery listings |
Copy config.toml.example to config.toml or ~/.config/apkmorph/config.toml.
Plugin registration is done in Python code (see Custom patch plugins above); no TOML entries required.
flowchart TD
APK[APK file] --> Analyzer[APKAnalyzer.decompile]
Analyzer --> Frida[observe_runtime() with Frida scripts]
Frida --> Report[AnalysisReport with runtime_observations]
Report --> Generator[PatchGenerator.from_description]
Generator --> LLM[LLMClient.query]
LLM --> Ollama[(Ollama<br>llama3.2 / gemma2 / phi3 / codellama)]
Generator --> Plugin[plugins.register_custom_patch_type]
Generator --> Gallery[gallery.get_template_by_id / import_template]
Generator --> Plan[PatchPlan]
Plan --> Validator[PatchGenerator.validate]
Validator --> Editor[SmaliEditor.apply_modification<br>(smali/xml/resource/manifest + plugins)]
Editor --> Builder[APKBuilder.rebuild_and_sign]
Builder --> Signed[patched_*.apk<br>(resources.arsc updated)]
Builder --> Device[install_on_device() via ADB<br>(install + optional launch)]
UI[Streamlit UI] -.-> Analyzer
UI -.-> Generator
UI -.-> Gallery
CLI[Typer CLI] -.-> Analyzer
CLI -.-> Generator
CLI -.-> Gallery
APKAnalyzer uses Apktool and Androguard to produce an immutable AnalysisReport (including string_resources). PatchGenerator sends enriched context to LLMClient, which returns a validated PatchPlan that may contain Smali, XML or resource modifications. SmaliEditor (extended for XML) applies minimal diffs to strings.xml and other resources; registered plugins are dispatched for custom edit_type values. APKBuilder assembles, aligns and signs the final APK (resources.arsc is regenerated by Apktool). All steps stay on the local machine. New install_on_device() uses adb install -r followed by am start when requested. PatchGenerator.apply_plan now automatically backs up the decompiled directory before edits and performs a full rollback on any rebuild/signing error. The UI now surfaces per-plan and per-modification confidence scores and feeds user comments back into the LLM system prompt for refinement. The new gallery module supplies curated, high-quality templates; PatchGenerator.import_template() provides the one-click import path used by both CLI and UI.
.
βββ pyproject.toml # Metadata, dependencies, CLI entry point
βββ config.toml.example # LLM, tools, signing, UI and gallery defaults
βββ src/apkmorph/
β βββ cli.py # Typer commands: analyze, patch, apply, explain, ui, batch, gallery
β βββ analyzer.py # APKAnalyzer with decompile(), find_by_keyword() and string resource extraction
β βββ llm.py # LLMClient.query() and patch prompt templates (now XML/resource aware)
β βββ patch_generator.py # PatchGenerator.from_description() + validate() + simulate_apply() + batch() + rollback support + gallery integration
β βββ models.py # AnalysisReport, PatchPlan, Modification (Pydantic) with edit_type support
β βββ plugins.py # Simple plugin API: register_custom_patch_type() and handler registry
β βββ gallery.py # Curated templates + one-click import helpers (new)
β βββ smali.py # SmaliEditor (extended for XML, resource string edits and custom plugins)
β βββ builder.py # APKBuilder.rebuild(), align_and_sign(), rebuild_and_sign() + install_on_device()
β βββ ui/app.py # Streamlit dashboard with uploader, diff viewer and gallery panel
β βββ utils.py # run_apktool(), run_adb(), generate_report_md(), safe_copytree()
βββ tests/
β βββ test_analyzer.py # Tests decompilation, component extraction, keyword search and string_resources
β βββ test_patch_generator.py # Prompt construction, validation, simulate_apply() for Smali+XML+resource + batch tests + device push + rollback + new gallery tests
βββ examples/
β βββ remove_ads.py # Runnable library example using natural-language API and gallery import
βββ LICENSE
pytest -qTests cover APKAnalyzer.decompile() accuracy on fixture APKs (including string_resources), cache hit/miss behaviour (including the new validity checks that skip Apktool for unchanged large APKs), parallel Smali extraction across multidex directories, PatchGenerator prompt construction for resource edits, PatchPlan validation, simulate_apply() dry-runs for XML/resource, the new batch() method (with full mocking), and the Frida runtime observation path (with realistic simulation fallback when the optional frida package is not installed). The new test_apply_plan_rollback_on_failure exercises the automatic backup/rollback path when rebuild_and_sign raises an error. The test_apply_plan_with_device_push (and related mocks for install_on_device) exercises the ADB integration. New tests for the feedback refinement loop, UI confidence element, and the curated gallery (test_get_gallery, test_import_template) have been added. Run with pytest -q --cov using the config in pyproject.toml.
- v0.1.0 β first release: Instant Ingestion, Natural Language, Code Reasoning, Precise Patches
- Add resource.arsc and XML intelligent editing with AI-suggested string changes
- Integrate Frida scripts to observe runtime behavior before suggesting patches
- Build interactive side-by-side Smali diff viewer with hover explanations
- Support additional local models (Gemma2, Phi3, CodeLlama) with auto-download
- Implement batch mode for applying the same natural-language patch to many APKs
- Create simple plugin API so users can register custom patch types (e.g. theme injectors)
- Add export of generated patches as reusable Python scripts or JSON templates
- Enable direct push to connected Android device with install + launch
- Improve error recovery with automatic rollback on rebuild failure
- Add confidence scoring UI element and user feedback loop to refine LLM prompts
- Optimize decompilation cache and parallelize analysis for large APKs (>50 MB)
- Publish curated patch template gallery that users can import with one click
- Add natural-language support for AndroidManifest.xml edits (permissions, activities, receivers) in PatchGenerator and SmaliEditor
- Extend plugin API so custom patch types can supply their own LLM prompt fragments for better domain-specific suggestions
- Add --verbose / --debug flag to all CLI commands with rich-formatted logging of each analysis and patching stage
- Implement response caching for identical natural-language + model combinations inside LLMClient to speed up repeated queries
- Expand test_patch_generator.py with new tests exercising manifest edits, plugin dispatch, and custom keystore flows
- Add troubleshooting section to README.md covering common Android SDK tool errors, cache issues, and model download failures
- Support environment-variable keystore passwords in APKBuilder.align_and_sign and document the pattern in config.toml.example
- Create a new example/plugin for injecting custom network security config XML via the plugin registry
π€ This roadmap is worked through continuously β ideas and PRs welcome!
Contributions are welcome and appreciated! Please read our CONTRIBUTING.md and adhere to the CODE_OF_CONDUCT.md. Good-first-issue PRs are especially encouraged β check the issue tracker for tagged tasks.
MIT Β© APK Morph Contributors β see LICENSE for details.