Skip to content

'android' branch update: Android Vector Math Preservation, Multi-LLM Engine Integration, Token Counter & CI Release Fixes - #14

Open
whooslizi wants to merge 36 commits into
breslee1707:mainfrom
whooslizi:android-dev
Open

'android' branch update: Android Vector Math Preservation, Multi-LLM Engine Integration, Token Counter & CI Release Fixes#14
whooslizi wants to merge 36 commits into
breslee1707:mainfrom
whooslizi:android-dev

Conversation

@whooslizi

@whooslizi whooslizi commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

PDF Vector Math Fix, ML Kit OCR, ONNX Layout, Multi-LLM Endpoints & CI Release

Summary

Adds Google ML Kit OCR fallback for scanned PDFs, integrates ONNX layout analysis, fixes vector math layout corruption, adds multi-LLM provider presets with connection testing and session token counts, and resolves the CI release artifact path issue.


Changes

1. ML Kit OCR Fallback for Scanned PDFs

  • Issue: Scanned or image-only PDF pages produced blank outputs due to missing text streams.
  • Fix: Wrapped Google ML Kit Text Recognition (OcrEngine.kt, OcrTextExtractor.kt) to kick in when a page contains no text. Bounding boxes and line structures are converted to TextBlock instances so translated text maps correctly onto the original scan layout. Added an on/off toggle in ControlsView.kt.

2. ONNX Layout Detection

  • Added ONNX Runtime document layout detection in AdvancedEngineManager.kt to identify multi-column structures, headers, footers, and captions before translation.

3. Vector Math Font Preservation

  • Issue: Stripping text streams on pages with equations wiped out or garbled native TeX math fonts (CMSY, CMMI, MSBM, eufm).
  • Fix: Pages flagged with hasMathInPage bypass stripTextFromPage. Standard text is covered via coverSourceText while leaving original vector math paths intact.

4. LLM Provider Presets & Testing

  • Added configurable endpoints and presets for:
    • Google Gemini (gemini-2.0-flash)
    • OpenAI (gpt-4o-mini, gpt-4o)
    • DeepSeek (deepseek-chat, deepseek-reasoner)
    • Groq (llama-3.3-70b-versatile)
    • OpenRouter
    • SiliconCloud (deepseek-ai/DeepSeek-V3)
    • Local endpoints (Ollama, LM Studio, vLLM)
  • Testing note: Implementations follow OpenAI-compatible and Gemini JSON schemas. Because active keys were not available for all services during development, endpoints like Groq and DeepSeek are implemented structurally and still need field testing with live user keys.

5. Connection Ping & Token Counter

  • Added a "Kiểm tra kết nối API" button in AiEngineSetupDialog to measure latency (ms) and validate API keys before running translations.
  • Added session-level tracking for prompt and completion tokens with a UI reset button.
  • Added a local fallback estimator (~3.8 chars/token) for endpoints that omit usage metadata in their responses.

6. In-Memory Key Security Notice

  • Updated the dialog notice in Vietnamese to make clear that API keys are stored only in RAM during the active session for direct client-to-provider HTTPS calls.

7. CI Release Fix (android-build.yml)

  • Issue: Top-level working-directory: android caused artifact bundling to fail during release publishing.
  • Fix: Scoped that working directory to the build job. The root publish job now properly picks up APKs (standard-debug, advanced-debug) into apks_dist/ for GitHub Releases.

File Changes

File Context
OcrEngine.kt ML Kit text recognition wrapper for image bitmap processing.
OcrTextExtractor.kt Maps OCR detections to TextBlock layout objects.
PdfLayoutPreserver.kt OCR fallback handling and math stream stripping bypass.
AiTranslateEngine.kt Provider endpoint mappings, latency test, and token usage parsing.
AiEngineSetupDialog.kt Provider presets UI, token tracking card, ping button, security notice.
ControlsView.kt Toggle switch for automatic OCR fallback.
AiTranslateEngineTest.kt Unit tests for fallback token estimation and session counter tracking.
.github/workflows/android-build.yml Fixed working-directory scoping for the publish step.

Testing

  • Ran ./gradlew test across all build variants (standardDebug, standardRelease, advancedDebug, advancedRelease) — all passing.
  • Tested OCR extraction on sample image-only PDFs.
  • Confirmed vector math retention on technical papers containing LaTeX equations.
  • Verified connection ping and latency measurement against live endpoints.

Review Checklist

  • ML Kit OCR properly triggers on non-selectable PDF pages.
  • Equations render cleanly without stripped math symbols.
  • Session token counts accumulate and reset properly.
  • In-app privacy disclaimer displays clearly.
  • CI workflow produces and attaches both APK flavors to releases.

…missing so APK is always signed and installable
- Set appVersionName to 0.2.1 (versionCode 201) for auto-update release.
- Implement OpenAiTranslateEngine supporting OpenAI, OpenRouter, DeepSeek, and local Ollama API endpoints with tag preservation system prompts.
- Add Engine Picker dropdown and LlmSettingsDialog modal in Android Compose UI to configure API key, base URL, and model name.
- Enhance isPureMathOrFormula in PdfLayoutPreserver to protect multiple choice option values, exponents, subscripts, and equation runs.
- Bump appVersionName to 0.3.0 (versionCode 300) for auto-update testing.
- Implement OcrTextExtractor using Google ML Kit Text Recognition for offline scanned PDF image translation.
- Add ONNX Runtime Android (DocLayoutDetector) and DocLayoutModelDownloader for 1:1 YOLOv8 neural layout detection.
- Integrate OCR fallback in PdfLayoutPreserver when PDF page text layer is empty.
- Implement OcrTextExtractor using Google ML Kit Text Recognition for offline scanned PDF image translation.
- Add ONNX Runtime Android (DocLayoutDetector) and DocLayoutModelDownloader with fallback URL endpoints for 1:1 YOLOv8 neural layout detection.
- Integrate OCR fallback in PdfLayoutPreserver when PDF page text layer is empty.
- Port Windows vflag() character-level formula detection into PageTextCollector using PDFBox TextPosition font, Unicode category, and glyph size checks.
- Emit {vN} formula placeholders for formula runs and restore them 1:1 using formulaVars.
- Remove fragile EXPONENT_PATTERN tag wrapping in FormulaPlaceholder.kt to eliminate tag distortion (e.g. garbled tag outputs).
- Refine isPureMathOrFormula so prose sentences containing math expressions or exponents are translated correctly with formulas preserved.
- Bump appVersionName to 0.3.1 (versionCode 301).
- Fix invalid GitHub Actions versions (@v6, @v7) in android-build.yml, release.yml, and macos-artifacts.yml.
- Prioritize direct HuggingFace layout model URLs in DocLayoutModelDownloader.kt to guarantee successful downloads.
Prevent raw placeholder leakage, preserve radical glyphs, add page selection and GitHub update system.
Full details of changes:
- Prevent internal placeholder leakage ({v71}, {v78}, {v81}, {v22}) on translation tag failure by falling back to clean source text.
- Preserve radical signs ('√'), superscripts, subscripts, and math symbols in sanitizeForFont without deleting characters.
- Add Excel-style page selection UI and parser supporting 'Tất cả các trang' or 'Từ X đến Y (bỏ Z)'.
- Guarantee unselected pages remain 100% untouched and preserved in exact order in output PDF.
- Configure update checker for GitHub Releases (https://github.com/breslee1707/VI-Translate/releases) with APK filtering.
- Update appVersionName to 0.3.6 and versionCode to 306.
- Eliminate stripTextFromPage to leave original vector math, fraction lines, radical symbols, and diagrams 100% intact.
- Mask only translated prose lines with white bounding box rectangles (coverSourceText).
- Auto-fit font sizes and align baselines for translated Vietnamese text.
- Enforce strict fail-safe tag error handling to prevent internal placeholder leakage.
…ssing

- Adjust coverSourceText padding to exact font bounds (padX=0.5f, padY=0.2f) to prevent bleeding into fraction lines.
- Convert positional sub/superscripts to inline Unicode tokens (², ³, ⁻, ₁, ₂) in writeString.
- Maintain pristine original vector math and fraction lines without text stream stripping.
…mode selector

- Add :advanced-engine plugin APK module with AIDL service contract.
- Add AdvancedEngineManager in :app to bind to AdvancedTranslationService via IPC file descriptors.
- Add Render Mode selector UI in ControlsView (Lightweight vs Advanced) with live addon detection status.
- Keep Lightweight Kotlin engine and all existing features 100% intact and lightweight.
…e, and dual APK CI workflow

- Add deploy-android.sh build & adb deployment script for app and advanced-engine modules.
- Refine UI wording to clean Vietnamese without emojis or technical slang, matching Image 1 card styling.
- Add AdvancedEngineStatus enum and AdvancedEngineSetupDialog.
- Add AppFontPreference setting (App Font vs Device System Font) in UI.
- Update GitHub Actions workflow to publish both Main App and Advanced Engine Addon release APKs.
…bind advanced engine state

- Enable vertical scrolling in MainActivity so UI controls and queue are scrollable on all screen sizes.
- Add debug signing fallback to advanced-engine build.gradle.kts so release APKs are signed and installable without errors.
- Bind advancedEngineMode StateFlow between TranslationController, MainViewModel, and MainActivity.
…de single APK

- Convert :advanced-engine to an Android Library module and include as dependency in :app.
- Deliver single unified APK (PDFTranslate-android-v0.3.6.apk) containing both Basic and Advanced engines.
- Update deploy-android.sh and GitHub Actions workflow for single APK release assets.
… mergeDexRelease duplicate class error

- Remove duplicate AIDL files from android/app/src/main/aidl.
- Keep AIDL contracts defined solely in :advanced-engine library module.
- Fix DexMergingTaskDelegate duplicate class error during assembleRelease.
… and fix DexMerging duplicate AIDL class error

- Route Nâng cao mode in TranslationController to AdvancedPdfTranslator.
- Implement multi-line paragraph block assembly and TeX formula tag safety validation.
- Remove duplicate AIDL files from app module.
- Release v0.3.6 single unified APK containing both Basic and Advanced engines.
…dvancedPdfTranslator to match Windows pdf2zh fallback rules

- Add font glyph encoding check before rendering text with PDFBox showText.
- Map unencodable math glyphs (∞ -> inf, ≤ -> <=, ≥ -> >=, ≠ -> !=, ± -> +/-) to match Windows pdf2zh font fallback rules.
- Prevent IllegalArgumentException during PDF page rendering.
…tering in Advanced engine

- Add exact white-background bounding box masking to completely erase original English text underneath translated text.
- Replace page-wide over-merging with line-block clustering to prevent giant paragraph blocks.
- Preserve formula protection and math glyph fallback rules.
…nate double-text scramble

- Route all translation requests through PdfLayoutPreserver.
- Eliminate 522-block over-fragmentation and double-text overlay.
- Remove experimental AdvancedPdfTranslator.
…fLayoutPreserver

- Fix continues() in groupIntoParagraphs to join multi-line math exam questions into complete sentences.
- Prevent trailing English sentence endings (equal, the equation is) from fragmenting.
- Preserve table row separation and pass all unit tests.
… placeholders

- align FormulaPlaceholder.kt with desktop engine rules to fix equation translation
- add fail-safe ML Kit OCR text extraction
- add standard and advanced productFlavors for dual APK testing
- add AiTranslateEngine for OpenAI, Gemini and custom LLMs with ephemeral key security
- Fix action versions to supported major releases (@v4 and @v2)
- Flatten APK output paths into apks_dist directory before artifact upload
- Configure softprops/action-gh-release to attach all collected APKs with fail_on_unmatched_files set to true
… and automatic ML Kit OCR for scanned pages

- Add engine selection UI row and AI configuration dialog (OpenAI/Gemini/Custom Endpoint)
- Store ephemeral AI API tokens in memory for translation sessions
- Wire up automatic ML Kit OCR text recognition for scanned image-only PDF pages
…and expand LLM providers

- Fix math equation stripping by preserving original PDF stream operators for formula blocks
- Avoid font sanitisation data loss on unencodable math symbols and Greek letters
- Add DeepSeek (V3/R1), Gemini 2.0/1.5, OpenRouter, Groq, SiliconCloud, and Custom LLM presets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant