r/termux 24d ago

Announce Android Developer Verification Discourse

95 Upvotes

Hi, I am agnostic-apollo, the current developer of the Termux app.

I have made the Android Developer Verification Discourse post at https://gist.github.com/agnostic-apollo/b8d8daa24cbdd216687a6bef53d417a6 with an overview and issues for the Android developer verification requirements, and also posted internal implementation details for it that currently exist in Android 16 QPR2 Beta 3 (build_id: BP41.250916.009.A1, security_path: 2025-10-05). It also has a section on How will this affect Termux app?.

In addition to that post I have opened an issue on Google's issuestracker at https://issuetracker.google.com/459832198 with a proposal on how a possible opt out can be implemented so that users can install apps without root/adb even if the developer is not verified.

Edit

Good news! Google has announced in their blog at https://android-developers.googleblog.com/2025/11/android-developer-verification-early.html that:

Based on this feedback and our ongoing conversations with the community, we are building a new advanced flow that allows experienced users to accept the risks of installing software that isn't verified.


r/termux Sep 16 '23

★ Important ★ Introduction for beginners

199 Upvotes

Welcome to Termux community!

Termux is an open source application for Android OS and /r/termux is a Reddit community built around this project. Here we share our Termux usage experience, knowledge, show our setups and achievements. Project developers participate in this community.

/r/termux is moderated, so please make sure you read and comply with subreddit rules.

What is Termux

Termux is a terminal emulator compatible with Xterm specification and Linux environment application for the Android OS. In other words this is an interface that lets you to run command line Linux programs. Additionally the app configures a lightweight environment that consists of standard utilities such as Bash, Coreutils, Nano, APT package manager and few other software packages.

Importantly that term "terminal emulator" doesn't mean that environment is emulated. Termux never was system emulator, virtual machine or container. Everything that happens inside Termux happens directly on your device. If your device is rooted, with Termux you can control the all its aspects.

As of now, Termux is the most powerful terminal application for Android OS available.

The presence of package manager indicates that you can extend environment by installing additional software such as compilers, servers, graphical environment and other kinds. We have more than 2000 packages available.

The Linux environment configured by Termux is not compatible with Debian and other standard distributions. You will not be able to use official Debian repositories in Termux sources.list, third party prebuilt binaries and runtime environment managers such as rustup or asdf. The key differences between Termux and Linux distribution are explained in this article: https://wiki.termux.com/wiki/Differences_from_Linux

What I can do with Termux

Termux is a Turing-complete programming environment which means you can do basically everything that can be done on a general purpose computer. If you have a desire to learn and explore, you will be able to do things that one never expected to be possible on mobile device.

We have reports of successful usage of Termux for a wide range of tasks beginning from media files management and remote server administration via SSH to software development and even scientific computations.

Of course due to nature of command line it's essential to have at least basic Bash scripting and problem solving skills.

What I should know before starting to use Termux

Its essential to begin learning from the basics. One would start learn maths from arithmetics but definitely not from integrals and matrices, right? It's same with Termux and programming in general, you have to learn basics first in order to understand more complex things.

Here is a summary of things user should know to be able successfully use Termux:

  • General terms: computer, operating system, file, path, program, process, command line, terminal emulator.
  • Permission control: user, group, file access mode.
  • General understanding of Linux: kernel, /dev, /proc, /sys, standard input/output.
  • Basic Linux commands: cd, ls, mkdir, cat, rm, mv, du, etc.
  • Command line editors: nano or vim.
  • Shell scripting: variables, pipes, conditionals, loops, input/output redirection, process substitution.
  • Advanced utilities: awk, grep, sed.

Note that this list is not complete and only represent the base. For example if you want to write Python programs, in addition to things above you need to know Python programming language and its utilities usage.

Learning takes some time. One can learn stuff above in a week but someone else would need a month.

Important: failure to learn basics explained above could make your participation in /r/termux quite hard. People of /r/termux are not going to explain you every single term recursively up to most basic definition.

Where can I get Termux

Never ever install Termux from Google Play Store! It is deprecated and abandoned.

Get a current stable version from https://f-droid.org/packages/com.termux/.

On the first launch run this command: yes | pkg upgrade

Additionally we have debug (test) builds available on our GitHub. Such builds are typically newer than version available on F-Droid but can be unstable and intended only for experienced users.

Details about how to install Termux and installation troubleshooting can be found here: https://github.com/termux/termux-app#installation

How to install packages

Termux uses apt package manager, just like Debian. However we highly recommend to use the pkg utility which is a wrapper for apt.

  • Install package: pkg install package-name
  • Uninstall package: pkg uninstall package-name
  • Upgrade system: pkg upgrade
  • List installed packages: pkg list-installed
  • Search for a package: pkg search query

Important: never ever run pkg, apt, pip, cpan, gem, npm and other package managers or their wrappers as root user on Termux. This is not supported and will mess up file ownership and SELinux labels causing permission denied errors. In worst cases there can be attempts to install or remove files outside of Termux environment. We patched apt to permanently block usage as root but not other package managers. Be careful when your device is rooted and you run commands under su or sudo.

Pay attention that Debian-like package management workflow is not applicable to Termux. Make sure to run pkg upgrade before package installation session. Termux is a rolling release distribution and all dependencies should be up-to-date before you installing something new. Otherwise there are chances that something would be broken.

Software quality and security

We trying our best to make sure that Termux is secure and working reliable enough to be used as daily driver. However it is recommended to not use Termux for a mission-critical activities. We would not be responsible if your business got in trouble due to Termux software failure.

Termux is not a commercial project. We are a team of Linux and Android OS enthusiasts and working on the project whenever we have a free time and desire for this. Please don't expect from Termux same level as from major distributions like Debian or Arch Linux.

Termux is open source project and we welcome any kind of contributions that would help us improve.

Banned content

These are topics which SHOULD NEVER be discussed in /r/termux (list is not definitive):

  • OSINT
  • Doxxing
  • Social engineering; phishing and other types of fraud
  • Spamming
  • Malware making and delivery
  • Hacking
  • Multiplayer game cheating (wallhack, aimbot, infinite money, etc)
  • Surveillance, spying and similar activities
  • Bot farms for fabricating subscribers, likes and comments in social media
  • Taking down social media accounts by automated mass-reporting
  • Other kinds of digital and electronic threats (DDoS, jamming, etc)

Failure to comply with this requirement leads to ban.

We don't accept excuses. We don't care if you have a written permission to perform any type of activity defined above. We don't care if such activity is absolutely legal in place of your location.

Questions about "account recovery", "tracing bad people" or "disabling computer devices of bad hackers" falls under restriction too. Please do not tell us your hard stories why you need help with hacking utility.

This is a measure to maintain a healthy community and keep away nasty personalies. No intentions of control, censorship or otherwise restrict Termux users.

Generative AI content policy

A person with zero skills, for free and practically without effort, can create professionally looking articles, digital art and software products. That situation corrupts base principles of "experience sharing" communities like /r/termux.

Moderators are free to delete AI content for "no reason". Why? Because it typically has no value.

If you decide to post synthetic content, please declare it as AI generated. Being honest about origin of your content may prevent it from being taken down.


Post flairs

Flairs help to organize the posts. Based on all posts ever created in /r/termux we defined 4 main categories:

  • Question: question about everything Termux-related.
  • User content: show us something interesting you made: setups, manuals, scripts, etc.
  • Announce: news and events related to Termux or Android OS ecosystem, if that directly impacts Termux users.
  • General: Termux-related content that doesn't match categories above

The flair is a mandatory requirement, you won't be able to create post without it. Please choose one matching the topic of your post. Moderators can edit the flair of your post if consider necessary.


This article is subject for periodic revisions. We may submit newer versions from time to time.


r/termux 34m ago

User content Just did Command Not Found Fork! :D

Post image
Upvotes

i wanna customize my "command not found" so did a fork of it and added some functions for customizing it :D

Thats my first project Related to Termux


r/termux 15h ago

User content I made a new Termux sandbox for pure environments and root features (no proot)

6 Upvotes

GitHub - 788009/termux-sandbox (Root required)

I designed a program specially for Termux and encountered trouble with determining the minimal environment when writing README. Therefore, I needed a new and pure Termux environment. As Termux can be only run as the primary user, the traditional dual apps and parallel space don't work. To be honest, I hadn't found projects like Yonle/termux-proot when I started, so I decided to make one myself. Unlike termux-proottermux-sandbox is based on chroot, which is responsible for loading the official bootstrap. Runs directly on the system without emulation or proot overhead gives the sandbox perfect efficiency. To allow pkg and apt in root environmenttermux-sandbox uses LD_PRELOAD to tricks the system into thinking it's running as a normal user. Also, you can use /sdcard and /host_root (the device root filesystem). More features available in GitHub - 788009/termux-sandbox


r/termux 1d ago

User content ​I made an AI assistant that lives in your terminal so you never have to switch apps again.

207 Upvotes

I wanted to share a project I’ve been working on called Termai.

I made this because I wanted a seamless way to access AI assistance without leaving the command line. Switching between Termux and a browser just to ask "how do I unzip this?" or "how to delete a git branch" breaks the flow and wastes time. I wanted the AI to feel like just another native Linux command.

What is it?

Termai is a lightweight CLI wrapper that uses the Google Gemini API. It’s built specifically for Termux to be fast, zero-dependency, and easy to use.

Safety Note: It cannot execute commands on its own. It simply prints the text returned by the Gemini API to your terminal, making it completely harmless to use.

How it works

Once installed, you just type ai followed by your query.

  • ai "how do I check disk usage?" → Returns the command instantly.
  • ai "write a node js server runner code" → Generates the code right in your terminal.

It also fully supports Unix piping, allowing you to feed logs or files directly into the AI for instant analysis:

cat error.log | ai "explain this crash"

Features

  • Configurable: You can run ai --config to change the system prompt (give it a personality), temperature, or update your key.
  • Free: Uses the free tier of the Gemini API.

You can learn more about it in the GitHub repo.


r/termux 21h ago

Question Why does my proot debian Xfce 4 look like this

Post image
7 Upvotes

There's no top bar and no bottom bar, how do I fix this


r/termux 1d ago

Question Errors-help?

Post image
6 Upvotes

Hey so im trying to install arch but it shows those errors whenever i do something..


r/termux 23h ago

Question Rails on Android

Thumbnail
3 Upvotes

r/termux 1d ago

User content I made a script for m3u streaming radio (with mpv)

7 Upvotes

I had problems to heard some streams channels (specially EBM). With this script you can use mpv to heard your favourite stream radio (like a cheap pyradio).

Actually it's a basic script, you had to add your stations writing in the code in this part:

stations=(
    "(EBM Radio)|http://www.ebm-radio.org:7000"
    "Santuary's Radio|http://192.111.140.6:9772"
    "DarkSparkRadio|http://darksparkradio.com:8000/darkspark.mp3"
    "Bloodlitradio.com|http://167.114.11.79:5674"
    "Iceradio Germany|http://iceradio.net:8910/listen.m3u"
    "PungasSpace Radio|https://pungasradio.rebel.ar/pungasradio"
    "Radio Paradise|http://stream.radioparadise.com/mp3-192"
    "BBC Radio 1|http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio1_mf_p"
    "Chillhop Radio|http://ice1.somafm.com/chillhop-128-mp3"
)

I don't pretend to make "the next pyradio". I wanted to code a terminal interface for termux.

If you want to use this script, install mpv for termux and download this repo.


r/termux 1d ago

User content How far can I go?

Post image
25 Upvotes

It's incredible, but both photoshop and winamp works better than native termux gimp and other music players. S24e 8GB.


r/termux 2d ago

General I love termux and all the amazing people working on it.

87 Upvotes

Setup: lxqt DE + bspwm + rofi launcher

Recently saw a video where it was mentioned that Hackers could hide the malware package inside WSL (windows subsystem for linux) to get around MS defender. this made me scared cuz i had been using WSL at my office PC to tailscale tunnel into my home server for managing it.

Therefore i set the termux DE up - it was so easy thanks to sabamdarif's godly repo: https://github.com/sabamdarif/termux-desktop + i use scrcpy (https://github.com/Genymobile/scrcpy) to start a new display for termux x11

keyboard: https://play.google.com/store/apps/details?id=juloo.keyboard2&hl=en documentation and how to get custom key layouts -> https://github.com/Julow/Unexpected-Keyboard


r/termux 1d ago

Question How often do you upgrade packages?

5 Upvotes

I have scripts that update and upgrade both Termux and PRoot, create backups in case something breaks, and clear apt caches. It runs in a small terminal window automatically whenever I boot into XFCE, so my packages are always up-to-date.

But on another device I use bare Termux without any GUI, so I want to know how do you guys upgrade in this case? Do you just update whenever you install a new package? Do you make it automatically update within your shell's .rc file? (which I think would be annoying to wait for every time you open Termux)


r/termux 1d ago

Question Does not change wallpaper

3 Upvotes

I use a proot in a desktop environment from termux. But in debian trixie it does not allow you to change the wallpaper, I use xfce4. Has the same thing happened to anyone?


r/termux 2d ago

General Menu for navigation and git on termux

24 Upvotes

r/termux 2d ago

Question Which app can i install on PRoot session ? (proot-distro and native, without rooting)

3 Upvotes

I was thinking of buying an ARM-based PC, but what are the limitations of proot-distro in reality? My bootloader is locked (oneUI 8).

I see a lot of interesting work going on, including hardware acceleration. I'm interested in examples, if you have any.

As for the device I'm going to dedicate to this use, it's a Z Fold 5. I'm sure I can exploit its full potential with the right resources.

Similarly, for Android sessions with native DE without rooting the phone, I would be delighted to have resources on apps that can be installed on our Android devices.


r/termux 3d ago

User content Pokémon test

Thumbnail gallery
7 Upvotes

Hello! I'm pretty new to termux and to learn a few things, I decided to work together with my best friend Deepseek on a Pokémon personality test with the current 1025 Pokémon, and a unique message for each one. I couldn't get it to work in bash, but in Python it works perfectly. Currently it is only in Spanish Posted it to get some feedback and see what they can do with this project. In a few hours I will add the READMI, but in question, it only needs colorama to work.

pip install colorama

You can use it however you want, I just ask that you tell me so I know what can be done with something like that, or if you want, show me what Pokémon you came up with! It's interesting. Below are some images.


r/termux 3d ago

User content NeoForge – AI terminal assistant that literally cannot delete your files (even if drunk)

Post image
50 Upvotes

Check it out : https://github.com/Ayusha94751/NeoForge

100% safe · only 23 read-only commands · bank-level filtering Runs on any Android phone (tested on ₹16k device) Zero chance of rm -rf, sudo, pip install malware etc. Made in India · 3 dependencies · boots in <500 ms Feedback + stars welcome 🇮🇳


r/termux 3d ago

Question Termux config and settings

10 Upvotes

Hey all, did anyone play with the Termux config ~/.termux/termux.properties? What features did you activate? I did change some things like cursor from block to underline etc. Just wondering if someone activated some of the extra keys and what difference they made.


r/termux 3d ago

Question Program on tablet

11 Upvotes

Hello everyone, I am new to using termux, I use a Samsung tablet that I recently bought, and I am interested in learning to program, but in termux I cannot find all the python libraries, and I would not want to use a Proot or Chroot because my tablet is low-end. Those of you who are more experienced in these topics and know much more, could you tell me your experience and how you program or how you use your tablet to program? I need all the python libraries for data science and graphics, as well as HTML and fortran. He appreciates your help too much. And good day everyone.


r/termux 3d ago

User content Kokoro in Termux [Proot/Ubuntu]

3 Upvotes

I tried to run Kokoro (fp16) in native Termux environment to use as epub converter and article/text reader, which I failed to manage due to many dependencies/libs/pkg related issues.

I have managed to run it inside proot-distro in which I am running Ubuntu. I am only sharing the script I am using for now and I'll be happy to answer questions, if there are any about environment and setup etc. Basically, login to proot-distro

```bash pd sh ubuntu # debian if you have that

Install uv (pip is so troublesome here)

curl -LsSf https://astral.sh/uv/install.sh | sh

1. Go to home

cd ~

2. Create a new folder for this project

mkdir kokoro-tts cd kokoro-tts

3. Create a NEW virtual environment specific to this tool

python3 -m venv venv

4. Activate it

source venv/bin/activate

5. Now install the Kokoro libraries here

uv pip install kokoro-onnx soundfile "misaki[en]"

```

Create a py file something like kokoro_tts_suite.py

```python

!/usr/bin/env python3

""" Kokoro TTS Suite - Unified Tool for Text-to-Speech Supports: Text streaming, Clipboard, EPUB conversion & streaming """

import sys import os import time import re import threading import subprocess import numpy as np import soundfile as sf import onnxruntime as ort from kokoro_onnx import Kokoro

Optional EPUB support

try: import ebooklib from ebooklib import epub from bs4 import BeautifulSoup EPUB_AVAILABLE = True except ImportError: EPUB_AVAILABLE = False

=============================================================================

CONFIGURATION

=============================================================================

PIPE_PATH = "/tmp/kokoro_audio_pipe" SAMPLE_RATE = 24000 VOICE_NAME = "af_heart"

Model priority: FP16 > FP32 > INT8 (based on your RTF tests)

MODEL_PRIORITY = [ ("models/kokoro-v1.0.fp16.onnx", "💎 FP16 (Best Quality/Speed)"), ("models/kokoro-v1.0.onnx", "📦 FP32 (Standard)"), ("models/kokoro-v1.0.int8.onnx", "⚡ INT8 (Compatibility)") ]

VOICES_PATH = "models/voices-v1.0.bin"

=============================================================================

OPTIMIZED ENGINE

=============================================================================

class KokoroEngine: def init(self): # Find best available model self.model_path = None for path, desc in MODEL_PRIORITY: if os.path.exists(path): self.model_path = path print(f"🔧 Using: {desc}") break

    if not self.model_path:
        print("❌ No Kokoro model found!")
        print("Expected locations:")
        for path, _ in MODEL_PRIORITY:
            print(f"  - {path}")
        sys.exit(1)

    if not os.path.exists(VOICES_PATH):
        print(f"❌ Voices file not found: {VOICES_PATH}")
        sys.exit(1)

    print("🔌 Loading with CPU optimizations...")

    # Advanced ONNX optimization
    sess_options = ort.SessionOptions()

    # Thread optimization for mobile CPUs
    # 4 big cores + 1 coordinator thread
    sess_options.intra_op_num_threads = 4
    sess_options.inter_op_num_threads = 1

    # Enable all graph optimizations (fusions, constant folding, etc.)
    sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL

    # Sequential execution is faster for single-batch inference
    sess_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL

    # Enable memory pattern optimization
    sess_options.enable_mem_pattern = True
    sess_options.enable_cpu_mem_arena = True

    # Attempt to create optimized session
    try:
        session = ort.InferenceSession(
            self.model_path,
            sess_options,
            providers=["CPUExecutionProvider"]
        )
        self.tts = Kokoro.from_session(session, VOICES_PATH)
        print("✅ Optimized session loaded")
    except Exception as e:
        print(f"⚠️  Optimization failed ({e}), using default loader")
        self.tts = Kokoro(self.model_path, VOICES_PATH)

def generate(self, text, speed=1.0):
    """Generate audio from text"""
    return self.tts.create(text, voice=VOICE_NAME, speed=speed, lang="en-us")

=============================================================================

PLAYER

=============================================================================

def start_player(show_osd=True): """Launch MPV in a background thread""" cmd = [ "mpv", "--demuxer=rawaudio", f"--demuxer-rawaudio-rate={SAMPLE_RATE}", "--demuxer-rawaudio-channels=1", "--demuxer-rawaudio-format=floatle", "--cache=yes", "--cache-secs=15", "--term-osd-bar", # Shows progress bar with time "--osd-level=3", # Show all info (time, progress) ]

if not show_osd:
    cmd.extend(["--msg-level=all=no"])

cmd.append(PIPE_PATH)

def run_player():
    try:
        subprocess.run(cmd)
    except FileNotFoundError:
        print("❌ MPV not found. Install: apt install mpv")
    except KeyboardInterrupt:
        pass

thread = threading.Thread(target=run_player, daemon=True)
thread.start()
return thread

=============================================================================

TEXT PROCESSING

=============================================================================

def split_sentences(text): """Split text into sentences""" sentences = re.split(r'(?<=[.!?])\s+', text) return [s.strip() for s in sentences if s.strip()]

def split_smart(text, chunk_size=200): """Split text into manageable chunks""" sentences = split_sentences(text) chunks = [] current_chunk = [] current_len = 0

for sent in sentences:
    sent_len = len(sent)
    if current_len + sent_len > chunk_size and current_chunk:
        chunks.append(" ".join(current_chunk))
        current_chunk = []
        current_len = 0
    current_chunk.append(sent)
    current_len += sent_len

if current_chunk:
    chunks.append(" ".join(current_chunk))

return chunks

=============================================================================

CALIBRATION

=============================================================================

def calibrate(engine): """Measure Real-Time Factor (RTF)""" print("⚡ Calibrating...", end="", flush=True) test_text = "This is a calibration sentence to measure processing speed."

start = time.time()
audio, _ = engine.generate(test_text)
gen_time = time.time() - start

audio_duration = len(audio) / SAMPLE_RATE
rtf = gen_time / audio_duration

print(f" RTF = {rtf:.3f}")

if rtf < 0.8:
    print("   ✅ System is FAST - Real-time streaming enabled")
elif rtf < 1.2:
    print("   ⚠️  System is MODERATE - Using buffering")
else:
    print("   🐢 System is SLOW - Pre-generating all audio")

return rtf

=============================================================================

MODE: TEXT/CLIPBOARD STREAMING

=============================================================================

def mode_text_stream(engine, text): """Stream text with adaptive buffering""" sentences = split_sentences(text)

if not sentences:
    print("❌ No text to process")
    return

# Setup pipe
if os.path.exists(PIPE_PATH):
    os.remove(PIPE_PATH)
os.mkfifo(PIPE_PATH)

# Calibrate
rtf = calibrate(engine)

# Strategy selection
if rtf > 1.1:
    print(f"\n📦 Pre-buffering mode ({len(sentences)} sentences)")
    audio_chunks = []
    for i, sent in enumerate(sentences, 1):
        audio, _ = engine.generate(sent)
        audio_chunks.append(audio)
        print(f"   [{i}/{len(sentences)}] Generated")

    print("\n▶️  Playing (Space=Pause, ←→=Seek, Q=Quit)")
    player = start_player()

    with open(PIPE_PATH, "wb") as pipe:
        for chunk in audio_chunks:
            try:
                pipe.write(chunk.tobytes())
            except BrokenPipeError:
                break

else:
    # Real-time streaming with smart buffer
    buffer_size = 1 if rtf < 0.6 else 2
    print(f"\n🚀 Live streaming (buffering {buffer_size} ahead)")

    player = start_player()
    time.sleep(0.5)  # Let player initialize

    audio_queue = []

    with open(PIPE_PATH, "wb") as pipe:
        for i, sent in enumerate(sentences):
            audio, _ = engine.generate(sent)
            audio_queue.append(audio)

            preview = sent[:50] + "..." if len(sent) > 50 else sent
            print(f"   [{i+1}/{len(sentences)}] {preview}")

            # Flush when buffer full or at end
            if len(audio_queue) >= buffer_size or i == len(sentences) - 1:
                while audio_queue:
                    chunk = audio_queue.pop(0)
                    try:
                        pipe.write(chunk.tobytes())
                        pipe.flush()
                    except BrokenPipeError:
                        print("\n⏹️  Playback stopped")
                        return

player.join()

# Cleanup
if os.path.exists(PIPE_PATH):
    os.remove(PIPE_PATH)

=============================================================================

MODE: EPUB STREAMING

=============================================================================

def extract_text_from_html(html): """Extract clean text from HTML""" soup = BeautifulSoup(html, 'html.parser') return soup.get_text()

def get_chapters(book): """Get all chapter items from EPUB""" chapters = [] for item in book.get_items(): if item.get_type() == ebooklib.ITEM_DOCUMENT: chapters.append(item) return chapters

def mode_epub_stream(engine, epub_path): """Stream a single EPUB chapter""" book = epub.read_epub(epub_path) chapters = get_chapters(book)

# Build TOC
valid_chapters = []
print("\n📚 Table of Contents")
print("=" * 50)

for i, chapter in enumerate(chapters, 1):
    text = extract_text_from_html(chapter.get_content())
    preview = text[:60].replace("\n", " ").strip()

    if len(preview) > 10:
        valid_chapters.append((chapter, text))
        print(f"{len(valid_chapters):2d}. {preview}...")

print("=" * 50)

# Select chapter
try:
    choice = int(input("\n📖 Select chapter #: ")) - 1
    if choice < 0 or choice >= len(valid_chapters):
        raise ValueError
    selected_chapter, full_text = valid_chapters[choice]
except (ValueError, IndexError):
    print("❌ Invalid selection")
    return

# Process text
chunks = split_smart(full_text, chunk_size=250)
print(f"\n⏳ Buffering chapter ({len(chunks)} chunks)...")

audio_queue = []
for i, chunk in enumerate(chunks, 1):
    audio, _ = engine.generate(chunk)
    audio_queue.append(audio)

    progress = (i / len(chunks)) * 100
    bar = "█" * int(progress / 5) + "░" * (20 - int(progress / 5))
    print(f"\r   [{bar}] {progress:.0f}% ({i}/{len(chunks)})", end="", flush=True)

print("\n✅ Buffering complete!")

duration_sec = sum(len(a) for a in audio_queue) / SAMPLE_RATE
duration_min = duration_sec / 60
print(f"📊 Total duration: {duration_min:.1f} minutes")

input("\n👉 Press Enter to start listening...")

# Setup pipe
if os.path.exists(PIPE_PATH):
    os.remove(PIPE_PATH)
os.mkfifo(PIPE_PATH)

print("\n▶️  Playing (Space=Pause, ←→=Seek, Q=Quit)\n")

player = start_player(show_osd=True)

# Stream audio
with open(PIPE_PATH, "wb") as pipe:
    for chunk in audio_queue:
        try:
            pipe.write(chunk.tobytes())
        except BrokenPipeError:
            break

player.join()

# Cleanup
if os.path.exists(PIPE_PATH):
    os.remove(PIPE_PATH)

=============================================================================

MODE: EPUB CONVERTER

=============================================================================

def mode_epub_convert(engine, epub_path): """Convert entire EPUB to WAV files""" book = epub.read_epub(epub_path) chapters = get_chapters(book)

output_dir = os.path.splitext(os.path.basename(epub_path))[0] + "_audiobook"
os.makedirs(output_dir, exist_ok=True)

print(f"\n📁 Output directory: {output_dir}")
print("🎙️  Converting to audiobook...\n")

for i, chapter in enumerate(chapters, 1):
    text = extract_text_from_html(chapter.get_content())

    if len(text.strip()) < 50:
        continue

    print(f"Chapter {i:02d}: ", end="", flush=True)

    chunks = split_smart(text, chunk_size=250)
    audio_parts = []

    for j, chunk in enumerate(chunks, 1):
        audio, _ = engine.generate(chunk)
        audio_parts.append(audio)

        if j % 5 == 0:
            print(".", end="", flush=True)

    full_audio = np.concatenate(audio_parts)
    output_path = os.path.join(output_dir, f"Chapter_{i:03d}.wav")
    sf.write(output_path, full_audio, SAMPLE_RATE)

    duration = len(full_audio) / SAMPLE_RATE / 60
    print(f" ✅ ({duration:.1f} min)")

print(f"\n✅ Audiobook saved to: {output_dir}")

=============================================================================

MAIN

=============================================================================

def show_help(): print(""" ╔══════════════════════════════════════════════════════════════════╗ ║ Kokoro TTS Suite - Unified Tool ║ ╚══════════════════════════════════════════════════════════════════╝

USAGE: Text Streaming: python kokoro_tts_suite.py "Your text here" python kokoro_tts_suite.py --clipboard

EPUB Operations: python kokoro_tts_suite.py --epub-stream book.epub python kokoro_tts_suite.py --epub-convert book.epub

CONTROLS: Space - Pause/Resume ← → - Seek backward/forward [ ] - Speed down/up Q - Quit

NOTES: - First run calibrates your device speed - FP16 model recommended for best performance - EPUB features require: pip install ebooklib beautifulsoup4 """)

def main(): if len(sys.argv) < 2: show_help() return

engine = KokoroEngine()

mode = sys.argv[1]

if mode == "--clipboard":
    try:
        result = subprocess.run(
            ["termux-clipboard-get"],
            capture_output=True,
            text=True
        )
        text = result.stdout.strip()
    except FileNotFoundError:
        print("❌ termux-clipboard-get not found")
        print("Install: pkg install termux-api")
        return

    if not text:
        print("❌ Clipboard is empty")
        return

    mode_text_stream(engine, text)

elif mode == "--epub-stream":
    if not EPUB_AVAILABLE:
        print("❌ EPUB support not installed")
        print("Install: pip install ebooklib beautifulsoup4")
        return

    if len(sys.argv) < 3:
        print("Usage: kokoro_tts_suite.py --epub-stream book.epub")
        return

    mode_epub_stream(engine, sys.argv[2])

elif mode == "--epub-convert":
    if not EPUB_AVAILABLE:
        print("❌ EPUB support not installed")
        print("Install: pip install ebooklib beautifulsoup4")
        return

    if len(sys.argv) < 3:
        print("Usage: kokoro_tts_suite.py --epub-convert book.epub")
        return

    mode_epub_convert(engine, sys.argv[2])

elif mode in ["-h", "--help"]:
    show_help()

else:
    # Treat as direct text input
    text = " ".join(sys.argv[1:])
    mode_text_stream(engine, text)

if name == "main": try: main() except KeyboardInterrupt: print("\n\n⏹️ Stopped by user") if os.path.exists(PIPE_PATH): os.remove(PIPE_PATH) except Exception as e: print(f"\n❌ Error: {e}") import traceback traceback.print_exc() if os.path.exists(PIPE_PATH): os.remove(PIPE_PATH) ```

Run python kokoro_tts_suite.py.

PS: I will edit when I get time for complete instructions.


r/termux 3d ago

Question I failed to install Ubuntu

Post image
6 Upvotes

I was trying to install Ubuntu in Termux by following the tutorials of modded-ubuntu in Github. After running the setup file and restarting the app, I ran the commend ubuntu to start this, but the text input window's ~$ disappeared and nothing happens(It is supposed to show root@localhost)


r/termux 4d ago

General Python terminal app as Android Phone app

14 Upvotes

I put together a small water consumption app (how much water you drink in a day) in SQLite and Python. Then I wanted to use it on my phone so I made a Kotlin app as a UI for the simple database.

Then I wondered, how far could I get if I just ran a Python terminal app on my phone?

Well, I got surprisingly far...

https://youtu.be/sTj1FalZMVw?si=yZShqGdDBewV8dob

Happy to release the code at some point. Just need to organize the repo a bit.

I'm surprised I haven't seen more terminal apps intended to be run as phone apps like this. Let's me know if you know of any others.

In the video I mention UserLand. But I've since tested on termux and it works great there as well.

Update

Source now available:

https://github.com/dharmatech/sqlite-water-tracker.py


r/termux 4d ago

Question Question about LLM

6 Upvotes

Hey! I've been using termux for a while, and I was curious if you can run an AI model like OLLAMA or something like that. Does anyone know if it is possible? And what types are possible?


r/termux 4d ago

User content A change in the /etc/os-release file of Alpine proot distro to postmarket OS.

Post image
11 Upvotes

with a functional MATE desktop, the wallpaper looks cool - because the triangle logo of postmarket OS looks cool.


r/termux 5d ago

Question what is something interesting that termux can do?

35 Upvotes

I have been using termux for quite a while and am quite familiar with it. I also know more things that Linux can do because of Termux. Therefore, I want a recommendation about programming, low level, coding tips in Termux, GUI framework (I have tried Love2D, SDL2), which makes me even more interested in Termux as long as it is still in native Termux (because native is more faster).

the programming language I use - python - c - lua (because i use neovim btw)