Update Web-LLM.py for windows

Updated input handling to use msvcrt
Modified get_multiline_input function
Updated system messages for Windows (CTRL+Z instead of CTRL+D)
Added Windows-specific checks
Removed Unix-specific imports
This commit is contained in:
Hafeez 2024-11-20 21:45:00 +05:30 committed by GitHub
parent 82e6321461
commit a53d85e284
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,4 +1,5 @@
import sys import sys
import msvcrt
import os import os
from colorama import init, Fore, Style from colorama import init, Fore, Style
import logging import logging
@ -12,10 +13,9 @@ from strategic_analysis_parser import StrategicAnalysisParser
from research_manager import ResearchManager from research_manager import ResearchManager
# Initialize colorama # Initialize colorama
if os.name == 'nt': # Windows-specific initialization if os.name != 'nt':
init(convert=True, strip=False, wrap=True) print("This version is Windows-specific. Please use the Unix version for other operating systems.")
else: sys.exit(1)
init()
# Set up logging # Set up logging
log_directory = 'logs' log_directory = 'logs'
@ -53,80 +53,67 @@ class OutputRedirector:
sys.stderr = self.original_stderr sys.stderr = self.original_stderr
def print_header(): def print_header():
print(Fore.CYAN + Style.BRIGHT + """ print(Fore.CYAN + Style.BRIGHT + """
🌐 Advanced Research Assistant 🤖 🌐 Advanced Research Assistant 🤖
""" + Style.RESET_ALL) """ + Style.RESET_ALL)
print(Fore.YELLOW + """ print(Fore.YELLOW + """
Welcome to the Advanced Research Assistant! Welcome to the Advanced Research Assistant!
Commands: Commands:
- For web search: start message with '/' - For web search: start message with '/'
Example: "/latest news on AI advancements" Example: "/latest news on AI advancements"
- For research mode: start message with '@' - For research mode: start message with '@'
Example: "@analyze the impact of AI on healthcare" Example: "@analyze the impact of AI on healthcare"
Press CTRL+D (Linux/Mac) or CTRL+Z (Windows) to submit input. Press CTRL+Z to submit input.
""" + Style.RESET_ALL) """ + Style.RESET_ALL)
def get_multiline_input() -> str: def get_multiline_input() -> str:
"""Get multiline input using raw terminal mode for reliable CTRL+D handling""" """Windows-compatible multiline input handler"""
print(f"{Fore.GREEN}📝 Enter your message (Press CTRL+D to submit):{Style.RESET_ALL}") print(f"{Fore.GREEN}📝 Enter your message (Press CTRL+Z to submit):{Style.RESET_ALL}")
lines = [] lines = []
current_line = []
import termios try:
import tty while True:
import sys if msvcrt.kbhit():
char = msvcrt.getch()
# Save original terminal settings # CTRL+Z detection (Windows equivalent of CTRL+D)
fd = sys.stdin.fileno() if char in [b'\x1a', b'\x04']: # CTRL+Z or CTRL+D
old_settings = termios.tcgetattr(fd) sys.stdout.write('\n')
if current_line:
lines.append(''.join(current_line))
return ' '.join(lines).strip()
try: # Handle special characters
# Set terminal to raw mode elif char == b'\r': # Enter
tty.setraw(fd) sys.stdout.write('\n')
lines.append(''.join(current_line))
current_line = []
current_line = [] elif char == b'\x08': # Backspace
while True: if current_line:
# Read one character at a time current_line.pop()
char = sys.stdin.read(1) sys.stdout.write('\b \b')
# CTRL+D detection elif char == b'\x03': # CTRL+C
if not char or ord(char) == 4: # EOF or CTRL+D sys.stdout.write('\n')
sys.stdout.write('\n') # New line for clean display return 'q'
if current_line:
lines.append(''.join(current_line))
return ' '.join(lines).strip()
# Handle special characters # Normal character
elif ord(char) == 13: # Enter elif 32 <= ord(char[0]) <= 126:
sys.stdout.write('\n') current_line.append(char.decode('utf-8'))
lines.append(''.join(current_line)) sys.stdout.write(char.decode('utf-8'))
current_line = []
elif ord(char) == 127: # Backspace sys.stdout.flush()
if current_line:
current_line.pop()
sys.stdout.write('\b \b') # Erase character
elif ord(char) == 3: # CTRL+C except Exception as e:
sys.stdout.write('\n') logger.error(f"Error in multiline input: {str(e)}")
return 'q' return 'q'
# Normal character
elif 32 <= ord(char) <= 126: # Printable characters
current_line.append(char)
sys.stdout.write(char)
# Flush output
sys.stdout.flush()
finally:
# Restore terminal settings
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
print() # New line for clean display
def initialize_system(): def initialize_system():
"""Initialize system with proper error checking""" """Initialize system with proper error checking"""
@ -296,7 +283,6 @@ def main():
if 'research_manager' in locals() and research_manager: if 'research_manager' in locals() and research_manager:
if hasattr(research_manager, 'ui'): if hasattr(research_manager, 'ui'):
research_manager.ui.cleanup() research_manager.ui.cleanup()
curses.endwin()
except: except:
pass pass
os._exit(0) os._exit(0)