Skip to content

Commit 198a47d

Browse files
committed
feat: Add Windows desktop app with system tray support
- Add app_desktop.py: Desktop wrapper with pystray system tray integration - Add PyInstaller spec files for building Windows .exe (single-file and folder versions) - Add build scripts (build.bat, build_onefile.bat) for easy compilation - Update translator.py: Fix duplicate imports, add debug_print for frontend logs - Update requirements.txt: Add pystray and Pillow dependencies - Update README.md: Document desktop app installation and usage - Update static/index.html: Frontend improvements - Update .gitignore: Exclude build artifacts and databases Desktop app features: - System tray icon for background operation - Server keeps running when browser is closed - Auto-opens browser on startup - Reopen anytime from tray icon menu - Clean quit via tray menu
1 parent 6e71d98 commit 198a47d

File tree

11 files changed

+1061
-68
lines changed

11 files changed

+1061
-68
lines changed

.gitignore

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,16 @@ logs/*
5050
!logs/.gitkeep
5151

5252
# Temporary files
53-
nltk_data/
53+
nltk_data/
54+
55+
# PyInstaller build files
56+
build/
57+
dist/
58+
*.spec.bak
59+
venv_build/
60+
*.manifest
61+
*.exe
62+
63+
# Keep spec files (they are configuration)
64+
!book_translator.spec
65+
!book_translator_onefile.spec

README.md

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,21 @@ ollama pull gpt-oss:20b
4444

4545
5. **Start the application**
4646

47-
**Option 1: Quick Launch (macOS)**
47+
**Option 1: Desktop App (Windows .exe)**
48+
49+
Download `BookTranslator.exe` from the Releases page or build it yourself:
50+
```bash
51+
pip install pyinstaller pystray Pillow
52+
pyinstaller book_translator_onefile.spec
53+
# The .exe will be in dist/BookTranslator.exe
54+
```
55+
Features:
56+
- System tray icon for background operation
57+
- Server keeps running when you close the browser
58+
- Reopen anytime from the tray icon
59+
- Right-click tray icon → "Quit Completely" to exit
60+
61+
**Option 2: Quick Launch (macOS)**
4862
```bash
4963
./Launch\ Book-Translator.command
5064
```
@@ -54,7 +68,7 @@ This will automatically:
5468
- Open http://localhost:5001 in your browser
5569
- Clear translation cache
5670

57-
**Option 2: Manual start**
71+
**Option 3: Manual start**
5872
```bash
5973
python translator.py
6074
# Then open http://localhost:5001 in your browser

app_desktop.py

Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
"""
2+
Book Translator Desktop Application
3+
====================================
4+
This file wraps the Flask application to run as a desktop app.
5+
Includes system tray support to keep the server running in background.
6+
"""
7+
8+
import sys
9+
import os
10+
import subprocess
11+
12+
# Determine if we're running as a packaged .exe
13+
if getattr(sys, 'frozen', False):
14+
# Running as packaged .exe (PyInstaller)
15+
BUNDLE_DIR = sys._MEIPASS
16+
APP_DIR = os.path.dirname(sys.executable)
17+
else:
18+
# Running as a normal Python script
19+
BUNDLE_DIR = os.path.dirname(os.path.abspath(__file__))
20+
APP_DIR = BUNDLE_DIR
21+
22+
# Change to the application directory
23+
os.chdir(APP_DIR)
24+
25+
# Create necessary folders if they don't exist
26+
for folder in ['uploads', 'translations', 'logs']:
27+
folder_path = os.path.join(APP_DIR, folder)
28+
os.makedirs(folder_path, exist_ok=True)
29+
30+
# Configure paths for translator.py
31+
os.environ['BOOK_TRANSLATOR_APP_DIR'] = APP_DIR
32+
os.environ['BOOK_TRANSLATOR_BUNDLE_DIR'] = BUNDLE_DIR
33+
34+
# Add directories to path
35+
sys.path.insert(0, APP_DIR)
36+
sys.path.insert(0, BUNDLE_DIR)
37+
38+
# Import the Flask application
39+
from translator import app, VERBOSE_DEBUG, Colors
40+
41+
# Import pystray for system tray
42+
try:
43+
import pystray
44+
from PIL import Image, ImageDraw
45+
HAS_PYSTRAY = True
46+
except ImportError:
47+
HAS_PYSTRAY = False
48+
print("pystray not installed, tray mode disabled")
49+
50+
import webbrowser
51+
import threading
52+
import time
53+
54+
# Global variables
55+
flask_thread = None
56+
tray_icon = None
57+
server_port = 5001
58+
APP_URL = f'http://localhost:{server_port}'
59+
60+
61+
def check_ollama():
62+
"""Check if Ollama is running"""
63+
import requests
64+
try:
65+
response = requests.get("http://localhost:11434/api/tags", timeout=2)
66+
return response.status_code == 200
67+
except:
68+
return False
69+
70+
71+
def print_banner():
72+
"""Display startup banner"""
73+
print(f"\n{Colors.CYAN}{'='*60}{Colors.RESET}")
74+
print(f"{Colors.BOLD}{Colors.GREEN} 📚 BOOK TRANSLATOR - Desktop Edition{Colors.RESET}")
75+
print(f"{Colors.CYAN}{'='*60}{Colors.RESET}")
76+
print(f" Version: 1.2.0 (Tray Mode)")
77+
print(f" Server: {APP_URL}")
78+
print(f" Working Directory: {os.getcwd()}")
79+
print(f"{Colors.CYAN}{'='*60}{Colors.RESET}\n")
80+
81+
82+
def create_app_icon():
83+
"""Create a proper icon for the application"""
84+
# Create a 256x256 image with transparency
85+
size = 256
86+
image = Image.new('RGBA', (size, size), (0, 0, 0, 0))
87+
draw = ImageDraw.Draw(image)
88+
89+
# Draw a book shape
90+
# Book cover (blue)
91+
draw.rounded_rectangle([20, 20, 236, 236], radius=20, fill=(41, 128, 185, 255))
92+
93+
# Inner cover highlight
94+
draw.rounded_rectangle([30, 30, 226, 226], radius=15, fill=(52, 152, 219, 255))
95+
96+
# Pages (white/cream)
97+
draw.rounded_rectangle([50, 40, 220, 216], radius=10, fill=(253, 253, 253, 255))
98+
99+
# Book spine (darker blue)
100+
draw.rounded_rectangle([20, 20, 60, 236], radius=10, fill=(31, 97, 141, 255))
101+
102+
# Text lines on pages
103+
line_color = (189, 195, 199, 255)
104+
y_positions = [70, 100, 130, 160, 190]
105+
for y in y_positions:
106+
width = 140 if y != 190 else 100
107+
draw.rounded_rectangle([75, y, 75 + width, y + 12], radius=3, fill=line_color)
108+
109+
# Translation arrow symbol (green)
110+
draw.polygon([
111+
(160, 85), (200, 128), (160, 171),
112+
(160, 145), (120, 145), (120, 111), (160, 111)
113+
], fill=(46, 204, 113, 255))
114+
115+
return image
116+
117+
118+
def create_tray_icon_image():
119+
"""Create a smaller icon for the system tray"""
120+
icon = create_app_icon()
121+
return icon.resize((64, 64), Image.Resampling.LANCZOS)
122+
123+
124+
def save_app_icon():
125+
"""Save the application icon as ICO file"""
126+
icon_path = os.path.join(APP_DIR, 'app_icon.ico')
127+
try:
128+
icon = create_app_icon()
129+
# Save with multiple sizes for ICO
130+
icon.save(icon_path, format='ICO', sizes=[(16, 16), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)])
131+
print(f"{Colors.GREEN}✓ Application icon saved: {icon_path}{Colors.RESET}")
132+
return icon_path
133+
except Exception as e:
134+
print(f"{Colors.YELLOW}⚠ Could not save icon: {e}{Colors.RESET}")
135+
return None
136+
137+
138+
def start_flask_server():
139+
"""Start Flask server in a separate thread"""
140+
print(f"{Colors.GREEN}🚀 Starting Flask server on port {server_port}...{Colors.RESET}")
141+
app.run(host='127.0.0.1', port=server_port, debug=False, use_reloader=False, threaded=True)
142+
143+
144+
def open_app_window(icon=None, item=None):
145+
"""Open the translator in the default browser"""
146+
print(f"{Colors.CYAN}🌐 Opening application in browser...{Colors.RESET}")
147+
try:
148+
webbrowser.open(APP_URL)
149+
print(f"{Colors.GREEN}✓ Browser opened successfully{Colors.RESET}")
150+
except Exception as e:
151+
print(f"{Colors.RED}✗ Could not open browser: {e}{Colors.RESET}")
152+
153+
154+
def quit_app(icon=None, item=None):
155+
"""Completely quit the application"""
156+
print(f"\n{Colors.YELLOW}👋 Shutting down Book Translator...{Colors.RESET}")
157+
if tray_icon:
158+
tray_icon.stop()
159+
os._exit(0)
160+
161+
162+
def create_tray_menu():
163+
"""Create the system tray menu"""
164+
return pystray.Menu(
165+
pystray.MenuItem("📖 Open Book Translator", open_app_window, default=True),
166+
pystray.Menu.SEPARATOR,
167+
pystray.MenuItem(f"🌐 Server: localhost:{server_port}", lambda: None, enabled=False),
168+
pystray.MenuItem("✅ Server Running", lambda: None, enabled=False),
169+
pystray.Menu.SEPARATOR,
170+
pystray.MenuItem("❌ Quit Completely", quit_app)
171+
)
172+
173+
174+
def run_with_tray():
175+
"""Run the app with system tray support"""
176+
global flask_thread, tray_icon
177+
178+
print(f"{Colors.GREEN}🚀 Starting in System Tray mode...{Colors.RESET}")
179+
print(f"{Colors.CYAN} The server runs in background.{Colors.RESET}")
180+
print(f"{Colors.CYAN} Close browser tab anytime - reopen from tray icon.{Colors.RESET}")
181+
print(f"{Colors.YELLOW} To fully quit: right-click tray icon → Quit Completely{Colors.RESET}\n")
182+
183+
# Save the application icon
184+
save_app_icon()
185+
186+
# Start Flask server in background thread
187+
flask_thread = threading.Thread(target=start_flask_server, daemon=True)
188+
flask_thread.start()
189+
190+
# Give server time to start
191+
print(f"{Colors.YELLOW}⏳ Starting server...{Colors.RESET}")
192+
time.sleep(3)
193+
194+
# Open browser window automatically
195+
print(f"{Colors.GREEN}✓ Server started!{Colors.RESET}")
196+
open_app_window()
197+
198+
# Create and run system tray icon
199+
icon_image = create_tray_icon_image()
200+
tray_icon = pystray.Icon(
201+
"BookTranslator",
202+
icon_image,
203+
"Book Translator - Click to Open",
204+
menu=create_tray_menu()
205+
)
206+
207+
print(f"\n{Colors.GREEN}{'='*60}{Colors.RESET}")
208+
print(f"{Colors.BOLD}{Colors.GREEN}✓ Book Translator is running!{Colors.RESET}")
209+
print(f"{Colors.GREEN}{'='*60}{Colors.RESET}")
210+
print(f" 🌐 URL: {APP_URL}")
211+
print(f" 📌 System tray icon active")
212+
print(f" 💡 Close browser anytime - server keeps running")
213+
print(f" 🔄 Click tray icon to reopen")
214+
print(f"{Colors.GREEN}{'='*60}{Colors.RESET}\n")
215+
216+
# Run the tray icon (this blocks but keeps the app alive)
217+
tray_icon.run()
218+
219+
220+
def run_simple():
221+
"""Run without tray (fallback)"""
222+
print(f"{Colors.GREEN}🚀 Starting Flask server...{Colors.RESET}")
223+
print(f"{Colors.CYAN} URL: {APP_URL}{Colors.RESET}")
224+
print(f"\n{Colors.RED} Press Ctrl+C to close{Colors.RESET}\n")
225+
226+
def open_browser():
227+
time.sleep(1.5)
228+
webbrowser.open(APP_URL)
229+
230+
threading.Thread(target=open_browser, daemon=True).start()
231+
app.run(host='127.0.0.1', port=server_port, debug=False, use_reloader=False)
232+
233+
234+
def main():
235+
"""Main entry point"""
236+
print_banner()
237+
238+
# Check Ollama
239+
print(f"{Colors.YELLOW}🔍 Checking Ollama...{Colors.RESET}")
240+
if check_ollama():
241+
print(f"{Colors.GREEN} ✓ Ollama is running{Colors.RESET}")
242+
else:
243+
print(f"{Colors.RED} ⚠️ Ollama not detected at localhost:11434{Colors.RESET}")
244+
print(f"{Colors.YELLOW} Please start Ollama before translating{Colors.RESET}")
245+
246+
print()
247+
248+
if HAS_PYSTRAY:
249+
run_with_tray()
250+
else:
251+
run_simple()
252+
253+
254+
if __name__ == '__main__':
255+
main()

app_icon.ico

109 KB
Binary file not shown.

0 commit comments

Comments
 (0)