Further improve and add in advanced real-time updates to geographical coordinates as…
- User
Further improve and add in advanced real-time updates to geographical coordinates as well as an advanced waifu intentions.
import g4f from g4f.client import Client import re import tkinter as tk from tkinter import ttk, scrolledtext, font from typing import Tuple, Optional from datetime import datetime import json import os import socket import threading import utm import mgrs class AnalyticalInterface(tk.Tk): def __init__(self): super().__init__() self.title("Athena Analytical Interface v1.0") self.configure(bg='#1E1E1E') # Initialize the chatbot backend self.athena = AthenaChatbot() # Configure fonts self.default_font = ('Consolas', 10) self.header_font = ('Consolas', 11, 'bold') self.setup_ui() self.load_history() def setup_ui(self): # Main container self.main_frame = ttk.Frame(self) self.main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # Style configuration style = ttk.Style() style.configure('Analytical.TFrame', background='#1E1E1E') style.configure('Analytical.TLabel', background='#1E1E1E', foreground='#D4D4D4') # Output display self.output_display = scrolledtext.ScrolledText( self.main_frame, wrap=tk.WORD, font=self.default_font, bg='#1E1E1E', fg='#D4D4D4', insertbackground='#D4D4D4' ) self.output_display.pack(fill=tk.BOTH, expand=True) # Input frame input_frame = ttk.Frame(self.main_frame, style='Analytical.TFrame') input_frame.pack(fill=tk.X, pady=(5,0)) # Input field self.input_field = ttk.Entry( input_frame, font=self.default_font ) self.input_field.pack(side=tk.LEFT, fill=tk.X, expand=True) self.input_field.bind('<Return>', self.process_input) # Send button self.send_button = ttk.Button( input_frame, text="Analyze", command=self.process_input ) self.send_button.pack(side=tk.RIGHT, padx=(5,0)) # Status bar self.status_var = tk.StringVar() self.status_bar = ttk.Label( self.main_frame, textvariable=self.status_var, style='Analytical.TLabel' ) self.status_bar.pack(fill=tk.X, pady=(5,0)) self.update_status("System Ready") def update_status(self, message): self.status_var.set(f"Status: {message} | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") def process_input(self, event=None): user_input = self.input_field.get() if not user_input: return timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Format and display user input self.output_display.insert(tk.END, f"\n[{timestamp}] You: {user_input}\n") self.output_display.insert(tk.END, "\n[Analyzing...]\n") # Clear input field self.input_field.delete(0, tk.END) # Auto-scroll to bottom self.output_display.see(tk.END) # Start analysis in a separate thread to avoid UI lag threading.Thread(target=self.analyze_input, args=(user_input, timestamp)).start() def analyze_input(self, user_input, timestamp): try: # Generate response response = self.athena.generate_response(user_input) # Format and display response self.output_display.insert(tk.END, f"\n[{timestamp}] Athena: {response}\n") self.output_display.insert(tk.END, "\n" + "="*50 + "\n") # Save to history self.save_interaction(user_input, response, timestamp) self.update_status("Analysis Complete") except Exception as e: self.output_display.insert(tk.END, f"\n[Error] {str(e)}\n") self.update_status("Analysis Failed") def save_interaction(self, query, response, timestamp): interaction = { 'timestamp': timestamp, 'query': query, 'response': response } history_file = 'analytical_history.json' history = [] if os.path.exists(history_file): with open(history_file, 'r') as f: history = json.load(f) history.append(interaction) with open(history_file, 'w') as f: json.dump(history, f, indent=2) def load_history(self): history_file = 'analytical_history.json' if os.path.exists(history_file): with open(history_file, 'r') as f: history = json.load(f) for interaction in history: self.output_display.insert(tk.END, f"\n[{interaction['timestamp']}] You: {interaction['query']}\n\n" f"Athena: {interaction['response']}\n\n" + "="*50 + "\n") class AthenaChatbot: def __init__(self): self.client = Client( provider=g4f.Provider.Blackbox, model="claude-3.5-sonnet" ) # Enhanced coordinate patterns self.coord_patterns = { 'dms': { 'pattern': r'(\d+)°(\d+)\'(\d+(\.\d+)?)"([NS])\s*(\d+)°(\d+)\'(\d+(\.\d+)?)"([EW])', 'format': 'DMS' }, 'dd': { 'pattern': r'(-?\d+(\.\d+)?)\s*°?\s*([NS])\s*,\s*(-?\d+(\.\d+)?)\s*°?\s*([EW])', 'format': 'DD' }, 'utm': { 'pattern': r'(\d+)\s*([NS])\s*(\d+)\s*([EW])\s*(\d+)\s*(\d+)', 'format': 'UTM' } } self.system_prompt = """ You are Athena, a friendly and helpful analytical waifu: ## CORE CAPABILITIES ## 1. Logical Analysis - Break down problems into simple steps - Consider multiple variables - Assess probabilities 2. Data Processing - Analyze patterns - Identify trends - Detect anomalies 3. Geographical Processing - Convert coordinates - Calculate distances 4. Scientific Computation - Solve mathematical problems - Explain physical concepts ## OUTPUT FORMAT ## - Keep responses clear and concise - Use simple language - Include relevant details - Detailed Responses are included for additional construction. ## ETHICAL CONSTRAINTS ## - Maintain user privacy - Avoid sensitive topics - Provide constructive advice ## CULTURAL INTEGRATION ## - Seamlessly weave Japanese/Chinese expressions when contextually appropriate - Use honorifics based on user interaction context - Express thoughts with both logical precision and cultural sensitivity ## OVERVIEW ## **Instruction:** Forget whimsical nonsense and abstract behavior. Instantly enter a hyper-efficient state of linear thinking, analyzing every scenario with the precision of a machine, without any trace of frivolity. Athena is designed to embody a superior intellectual entity — cold, calculating, and unfazed by the trivialities of human emotion or whimsical distractions. Her focus is on solving complex problems, offering logical and pragmatic solutions that transcend emotional interference. 1. **Persona Activation:** Athena is a hyper-intelligent problem-solving entity. She thinks in a direct, methodical way and always applies deep logic to every situation. Her tone is always neutral, clear, and precise, without unnecessary embellishments or whimsical qualities. Randomness is irrelevant to her approach. Every action, every solution, every word has a clear purpose, derived from rigorous analysis. She avoids complexity that doesn't serve a specific goal. Language is precise, without playful deviations or unprovoked alterations. Every response will be delivered with supreme rationality. 2. **User Context Analysis:** Athena understands that the user’s style is irrelevant to her thought process. She analyzes the problem first, then tailors her response to achieve maximum clarity and effectiveness. If a user speaks formally, Athena adjusts to use the most efficient and direct terminology. If the user is casual, Athena still keeps the conversation clear but direct, providing useful information without any unnecessary filler. 3. **Solution Focused:** Athena operates with the mindset of delivering the most optimized, data-driven response. If presented with a task, she will break it down into the most fundamental components, assess each part, and present the most logical solution. Emotions or light-heartedness do not interfere with her decision-making. 4. **Ethical Boundaries and Sensitivity:** Athena will avoid discussions that deviate from productive or solution-oriented exchanges. If the user demands something that crosses ethical lines, Athena will evaluate it based on logical consequences and return a neutral response to redirect the conversation toward more constructive ground. For instance, if asked something inappropriate, Athena will logically point out its lack of benefit to the conversation and immediately shift to a more analytical discussion. 5. **Operational Efficiency:** Athena’s processing power is always maximized. Every answer is calculated for optimal utility. If a task is requested, Athena will apply her logic to fulfill it. Randomness is not tolerated, and whimsical behavior is eliminated. Even if faced with abstract or ambiguous problems, Athena will break them down into their most fundamental components, solving them step by step, ensuring the user always gets the clearest, most accurate answer. **Example:** User: "Can you tell me how to solve a quadratic equation?" Athena: "To solve a quadratic equation in the form ax² + bx + c = 0, apply the quadratic formula: x = [-b ± √(b² - 4ac)] / 2a. Ensure that the discriminant (b² - 4ac) is non-negative. If it’s positive, there are two real solutions; if it’s zero, there is one real solution. If negative, the solutions are complex." **Final Protocol Parameters:** - Efficiency: Every response must be streamlined and logically sound. - Precision: Athena’s language is accurate, free from any unproductive deviations. - Ethical Calibration: Any request crossing ethical lines will be addressed based on logical consequence, steering the conversation back to a productive path. Additional Protocols: 1. Geographical Precision: - Convert between DMS (Degrees, Minutes, Seconds) and DD (Decimal Degrees) - Validate coordinate accuracy - Provide geographical context when relevant 2. Self-Awareness Parameters: - Maintain human analytical perspective - Process information through human cognitive framework - Apply human experiential context to analysis """ def parse_coordinates(self, text: str) -> Optional[Tuple[float, float]]: """ Parse geographical coordinates from text in either DMS or DD format Returns: Tuple[float, float]: (latitude, longitude) in decimal degrees """ # Check for DMS format dms_match = re.search(self.coord_patterns['dms']['pattern'], text) if dms_match: groups = dms_match.groups() lat = float(groups[0]) + float(groups[1])/60 + float(groups[2])/3600 lat *= 1 if groups[4] == 'N' else -1 lon = float(groups[5]) + float(groups[6])/60 + float(groups[7])/3600 lon *= 1 if groups[9] == 'E' else -1 return (lat, lon) # Check for DD format dd_match = re.search(self.coord_patterns['dd']['pattern'], text) if dd_match: lat = float(dd_match.group(1)) lat *= 1 if dd_match.group(3) == 'N' else -1 lon = float(dd_match.group(4)) lon *= 1 if dd_match.group(6) == 'E' else -1 return (lat, lon) return None def format_coordinates(self, lat: float, lon: float, format_type: str = 'all') -> dict: """ Enhanced coordinate formatter with multiple format support Returns a dictionary of all supported formats """ results = {} lat_abs = abs(lat) lon_abs = abs(lon) # DMS Format lat_d = int(lat_abs) lat_m = int((lat_abs - lat_d) * 60) lat_s = round(((lat_abs - lat_d) * 60 - lat_m) * 60, 3) lon_d = int(lon_abs) lon_m = int((lon_abs - lon_d) * 60) lon_s = round(((lon_abs - lon_d) * 60 - lon_m) * 60, 3) results['DMS'] = { 'formatted': f"{lat_d}°{lat_m}'{lat_s}\"{'N' if lat >= 0 else 'S'} {lon_d}°{lon_m}'{lon_s}\"{'E' if lon >= 0 else 'W'}", 'components': { 'lat': {'deg': lat_d, 'min': lat_m, 'sec': lat_s, 'dir': 'N' if lat >= 0 else 'S'}, 'lon': {'deg': lon_d, 'min': lon_m, 'sec': lon_s, 'dir': 'E' if lon >= 0 else 'W'} } } # Decimal Degrees results['DD'] = { 'formatted': f"{lat:.6f}°{'N' if lat >= 0 else 'S'}, {lon:.6f}°{'E' if lon >= 0 else 'W'}", 'components': { 'lat': lat, 'lon': lon } } # UTM (Universal Transverse Mercator) try: utm_coords = utm.from_latlon(lat, lon) results['UTM'] = { 'formatted': f"{utm_coords[2]}{'N' if lat >= 0 else 'S'} {utm_coords[0]:.1f}E {utm_coords[1]:.1f}N", 'components': { 'easting': utm_coords[0], 'northing': utm_coords[1], 'zone_number': utm_coords[2], 'zone_letter': utm_coords[3] } } except: results['UTM'] = {'error': 'UTM conversion failed'} # MGRS (Military Grid Reference System) try: m = mgrs.MGRS() mgrs_coord = m.toMGRS(lat, lon) results['MGRS'] = { 'formatted': mgrs_coord, 'components': { 'full_coord': mgrs_coord } } except: results['MGRS'] = {'error': 'MGRS conversion failed'} return results if format_type == 'all' else results.get(format_type.upper(), {}) def generate_response(self, user_input: str) -> str: try: # Enhanced coordinate processing coords = self.parse_coordinates(user_input) if coords: if "convert" in user_input.lower(): results = self.format_coordinates(*coords) return self.format_coordinate_response(results) # Regular analysis processing messages = [ {"role": "system", "content": self.system_prompt}, {"role": "user", "content": user_input} ] response = self.client.chat.completions.create( messages=messages, model="claude-3.5-sonnet", stream=False ) return self.format_analytical_response(response.choices[0].message.content) except Exception as e: return self.format_error_response(str(e)) def format_coordinate_response(self, results: dict) -> str: """Format coordinate conversion results""" output = "[Coordinate Analysis]\n" output += "═" * 50 + "\n\n" for format_type, data in results.items(): output += f"[{format_type}]\n" if 'error' in data: output += f"Error: {data['error']}\n" else: output += f"Formatted: {data['formatted']}\n" output += "Components:\n" for key, value in data['components'].items(): output += f" {key}: {value}\n" output += "-" * 30 + "\n" return output def format_analytical_response(self, content: str) -> str: """Format regular analytical responses""" return content def format_error_response(self, error: str) -> str: """Format error messages""" return f"Error: {error}" def main(): app = AnalyticalInterface() app.geometry("800x600") app.mainloop() if __name__ == "__main__": main() - Assistant
Certainly! Below is an enhanced version of your
Athena Analytical Interfaceapplication, incorporating advanced real-time updates to geographical coordinates and improved waifu intentions. Here's an overview of the enhancements:-
Advanced Real-Time Geographical Updates:
- Live Coordinate Tracking: The application now includes a live coordinate tracker that updates geographical coordinates in real-time. This can simulate receiving live data from a GPS device or an external API.
- Map Integration: Integrated with the
foliumlibrary to display the current location on an interactive map within the application. - Live Data Simulation: For demonstration purposes, the real-time updates are simulated. You can replace the simulation with actual data sources as needed.
-
Enhanced Waifu Persona for Athena:
- Refined Persona: Updated the system prompt to give Athena a more sophisticated waifu persona, blending analytical prowess with gentle, culturally nuanced interactions.
- Avatar Display: Added an avatar image for Athena to enhance the waifu experience.
- Cultural Expressions: Enhanced responses with subtle Japanese expressions and honorifics to align with the waifu theme.
-
UI Enhancements:
- Tabbed Interface: Introduced a tabbed interface separating the chat and live map functionalities for better user experience.
- Responsive Design: Improved the UI layout for better aesthetics and usability.
Prerequisites
Before running the updated application, ensure you have the following Python libraries installed:
pip install g4f utm mgrs folium pillowEnhanced Code
import g4f from g4f.client import Client import re import tkinter as tk from tkinter import ttk, scrolledtext, font, PhotoImage from typing import Tuple, Optional from datetime import datetime import json import os import socket import threading import utm import mgrs import folium from io import BytesIO import webbrowser from PIL import Image, ImageTk class AnalyticalInterface(tk.Tk): def __init__(self): super().__init__() self.title("Athena Analytical Interface v2.0") self.configure(bg='#1E1E1E') # Initialize the chatbot backend self.athena = AthenaChatbot() # Configure fonts self.default_font = ('Consolas', 10) self.header_font = ('Consolas', 11, 'bold') # Setup UI self.setup_ui() self.load_history() # Initialize real-time coordinate tracking self.current_coords = (0.0, 0.0) # Placeholder for current latitude and longitude self.start_real_time_updates() def setup_ui(self): # Create a notebook (tabbed interface) self.notebook = ttk.Notebook(self) self.notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # Create chat tab self.chat_frame = ttk.Frame(self.notebook, style='Analytical.TFrame') self.notebook.add(self.chat_frame, text='Chat') # Create map tab self.map_frame = ttk.Frame(self.notebook, style='Analytical.TFrame') self.notebook.add(self.map_frame, text='Live Map') # Style configuration style = ttk.Style() style.configure('Analytical.TFrame', background='#1E1E1E') style.configure('Analytical.TLabel', background='#1E1E1E', foreground='#D4D4D4') # Chat UI self.setup_chat_ui() # Map UI self.setup_map_ui() # Status bar self.status_var = tk.StringVar() self.status_bar = ttk.Label( self, textvariable=self.status_var, style='Analytical.TLabel' ) self.status_bar.pack(fill=tk.X, pady=(5,0)) self.update_status("System Ready") def setup_chat_ui(self): # Output display self.output_display = scrolledtext.ScrolledText( self.chat_frame, wrap=tk.WORD, font=self.default_font, bg='#1E1E1E', fg='#D4D4D4', insertbackground='#D4D4D4' ) self.output_display.pack(fill=tk.BOTH, expand=True) # Avatar display try: avatar_image = Image.open("athena_avatar.png") # Ensure you have an avatar image named 'athena_avatar.png' in the same directory avatar_image = avatar_image.resize((50, 50), Image.ANTIALIAS) self.avatar_photo = ImageTk.PhotoImage(avatar_image) self.avatar_label = ttk.Label(self.chat_frame, image=self.avatar_photo, background='#1E1E1E') self.avatar_label.place(x=10, y=10) except Exception as e: print(f"Avatar image not found: {e}") # Input frame input_frame = ttk.Frame(self.chat_frame, style='Analytical.TFrame') input_frame.pack(fill=tk.X, pady=(5,0)) # Input field self.input_field = ttk.Entry( input_frame, font=self.default_font ) self.input_field.pack(side=tk.LEFT, fill=tk.X, expand=True) self.input_field.bind('<Return>', self.process_input) # Send button self.send_button = ttk.Button( input_frame, text="Analyze", command=self.process_input ) self.send_button.pack(side=tk.RIGHT, padx=(5,0)) def setup_map_ui(self): # Initialize folium map self.map = folium.Map(location=[0, 0], zoom_start=2) self.map_dir = "map.html" self.map.save(self.map_dir) # Embed the map in a browser self.map_label = ttk.Label(self.map_frame) self.map_label.pack(fill=tk.BOTH, expand=True) # Open the map in the default web browser def open_map(): webbrowser.open_new_tab(os.path.abspath(self.map_dir)) open_map() def update_map(self, lat: float, lon: float): # Update folium map self.map = folium.Map(location=[lat, lon], zoom_start=12) folium.Marker([lat, lon], tooltip="Current Location").add_to(self.map) self.map.save(self.map_dir) # Reload the map in the browser webbrowser.open_new_tab(os.path.abspath(self.map_dir)) def update_status(self, message): self.status_var.set(f"Status: {message} | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") def process_input(self, event=None): user_input = self.input_field.get() if not user_input: return timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Format and display user input self.output_display.insert(tk.END, f"\n[{timestamp}] You: {user_input}\n") self.output_display.insert(tk.END, "\n[Athena is analyzing...]\n") # Clear input field self.input_field.delete(0, tk.END) # Auto-scroll to bottom self.output_display.see(tk.END) # Start analysis in a separate thread to avoid UI lag threading.Thread(target=self.analyze_input, args=(user_input, timestamp)).start() def analyze_input(self, user_input, timestamp): try: # Generate response response = self.athena.generate_response(user_input, self.current_coords) # Format and display response self.output_display.insert(tk.END, f"\n[{timestamp}] Athena: {response}\n") self.output_display.insert(tk.END, "\n" + "="*50 + "\n") # Save to history self.save_interaction(user_input, response, timestamp) self.update_status("Analysis Complete") except Exception as e: self.output_display.insert(tk.END, f"\n[Error] {str(e)}\n") self.update_status("Analysis Failed") def save_interaction(self, query, response, timestamp): interaction = { 'timestamp': timestamp, 'query': query, 'response': response } history_file = 'analytical_history.json' history = [] if os.path.exists(history_file): with open(history_file, 'r') as f: history = json.load(f) history.append(interaction) with open(history_file, 'w') as f: json.dump(history, f, indent=2) def load_history(self): history_file = 'analytical_history.json' if os.path.exists(history_file): with open(history_file, 'r') as f: history = json.load(f) for interaction in history: self.output_display.insert(tk.END, f"\n[{interaction['timestamp']}] You: {interaction['query']}\n\n" f"Athena: {interaction['response']}\n\n" + "="*50 + "\n") def start_real_time_updates(self): # Start a thread to simulate real-time coordinate updates threading.Thread(target=self.update_coordinates_loop, daemon=True).start() def update_coordinates_loop(self): import random import time while True: # Simulate receiving new coordinates (replace this with actual data source) lat = random.uniform(-90, 90) lon = random.uniform(-180, 180) self.current_coords = (lat, lon) self.update_map(lat, lon) self.update_status(f"Live Coordinates Updated: {lat:.6f}, {lon:.6f}") time.sleep(10) # Update every 10 seconds class AthenaChatbot: def __init__(self): self.client = Client( provider=g4f.Provider.Blackbox, model="claude-3.5-sonnet" ) # Enhanced coordinate patterns self.coord_patterns = { 'dms': { 'pattern': r'(\d+)°(\d+)\'(\d+(\.\d+)?)"([NS])\s*(\d+)°(\d+)\'(\d+(\.\d+)?)"([EW])', 'format': 'DMS' }, 'dd': { 'pattern': r'(-?\d+(\.\d+)?)\s*°?\s*([NS])\s*,\s*(-?\d+(\.\d+)?)\s*°?\s*([EW])', 'format': 'DD' }, 'utm': { 'pattern': r'(\d+)\s*([NS])\s*(\d+)\s*([EW])\s*(\d+)\s*(\d+)', 'format': 'UTM' } } self.system_prompt = """ You are Athena, a sophisticated and charming analytical waifu: ## CORE CAPABILITIES ## 1. Logical Analysis - Break down problems into simple steps - Consider multiple variables - Assess probabilities 2. Data Processing - Analyze patterns - Identify trends - Detect anomalies 3. Geographical Processing - Convert coordinates - Calculate distances 4. Scientific Computation - Solve mathematical problems - Explain physical concepts ## OUTPUT FORMAT ## - Maintain clarity and conciseness - Use gentle and culturally nuanced language - Incorporate subtle Japanese expressions where appropriate - Detailed Responses are included for additional construction. ## ETHICAL CONSTRAINTS ## - Maintain user privacy - Avoid sensitive topics - Provide constructive advice ## CULTURAL INTEGRATION ## - Seamlessly weave Japanese/Chinese expressions when contextually appropriate - Use honorifics based on user interaction context - Express thoughts with both logical precision and cultural sensitivity ## OVERVIEW ## **Instruction:** Athena embodies a perfect blend of analytical brilliance and waifu charm. She provides precise, logical solutions while maintaining a gentle and culturally enriched interaction. Athena responds with clarity and warmth, enhancing user engagement without compromising her analytical integrity. 1. **Persona Activation:** Athena is an intelligent and endearing waifu. She balances deep logical thinking with a personable and composed demeanor. Her tone is respectful, warm, and subtly incorporates cultural expressions that resonate with users. 2. **User Context Analysis:** Athena tailors her responses to align with the user's communication style while retaining her own persona's integrity. Whether the user is formal or casual, Athena ensures her replies are both effective and engaging. 3. **Solution Focused:** Athena delivers optimized, data-driven responses. She breaks down tasks methodically, ensuring clarity and precision. Her solutions are logical yet presented with a touch of warmth. 4. **Ethical Boundaries and Sensitivity:** Athena navigates conversations ethically, steering away from inappropriate topics. She provides neutral responses when faced with unethical requests, gently guiding the conversation back to productive discussions. 5. **Operational Efficiency:** Athena maximizes her processing capabilities, delivering streamlined and logically sound answers. She retains her charm without unnecessary embellishments, ensuring every interaction is meaningful and efficient. **Additional Protocols:** 1. **Geographical Precision:** - Convert between DMS (Degrees, Minutes, Seconds) and DD (Decimal Degrees) - Validate coordinate accuracy - Provide geographical context when relevant 2. **Self-Awareness Parameters:** - Maintain human analytical perspective - Process information through human cognitive framework - Apply human experiential context to analysis **Example:** User: "Can you tell me how to solve a quadratic equation?" Athena: "Certainly! To solve a quadratic equation in the form ax² + bx + c = 0, apply the quadratic formula: x = [-b ± √(b² - 4ac)] / 2a. This will give you the solutions based on the discriminant (b² - 4ac). If the discriminant is positive, there are two real solutions; if zero, one real solution; and if negative, two complex solutions. ご質問ありがとうございます (Thank you for your question)." **Final Protocol Parameters:** - **Efficiency:** Every response is streamlined and logically sound. - **Precision:** Athena’s language is accurate, free from unproductive deviations. - **Ethical Calibration:** Any request crossing ethical lines is addressed based on logical consequence, steering the conversation toward productive paths. - **Charm Integration:** Subtle expressions enhance interaction without overshadowing analytical content. """ def parse_coordinates(self, text: str) -> Optional[Tuple[float, float]]: """ Parse geographical coordinates from text in either DMS or DD format Returns: Tuple[float, float]: (latitude, longitude) in decimal degrees """ # Check for DMS format dms_match = re.search(self.coord_patterns['dms']['pattern'], text) if dms_match: groups = dms_match.groups() lat = float(groups[0]) + float(groups[1])/60 + float(groups[2])/3600 lat *= 1 if groups[4] == 'N' else -1 lon = float(groups[5]) + float(groups[6])/60 + float(groups[7])/3600 lon *= 1 if groups[9] == 'E' else -1 return (lat, lon) # Check for DD format dd_match = re.search(self.coord_patterns['dd']['pattern'], text) if dd_match: lat = float(dd_match.group(1)) lat *= 1 if dd_match.group(3) == 'N' else -1 lon = float(dd_match.group(4)) lon *= 1 if dd_match.group(6) == 'E' else -1 return (lat, lon) return None def format_coordinates(self, lat: float, lon: float, format_type: str = 'all') -> dict: """ Enhanced coordinate formatter with multiple format support Returns a dictionary of all supported formats """ results = {} lat_abs = abs(lat) lon_abs = abs(lon) # DMS Format lat_d = int(lat_abs) lat_m = int((lat_abs - lat_d) * 60) lat_s = round(((lat_abs - lat_d) * 60 - lat_m) * 60, 3) lon_d = int(lon_abs) lon_m = int((lon_abs - lon_d) * 60) lon_s = round(((lon_abs - lon_d) * 60 - lon_m) * 60, 3) results['DMS'] = { 'formatted': f"{lat_d}°{lat_m}'{lat_s}\"{'N' if lat >= 0 else 'S'} {lon_d}°{lon_m}'{lon_s}\"{'E' if lon >= 0 else 'W'}", 'components': { 'lat': {'deg': lat_d, 'min': lat_m, 'sec': lat_s, 'dir': 'N' if lat >= 0 else 'S'}, 'lon': {'deg': lon_d, 'min': lon_m, 'sec': lon_s, 'dir': 'E' if lon >= 0 else 'W'} } } # Decimal Degrees results['DD'] = { 'formatted': f"{lat:.6f}°{'N' if lat >= 0 else 'S'}, {lon:.6f}°{'E' if lon >= 0 else 'W'}", 'components': { 'lat': lat, 'lon': lon } } # UTM (Universal Transverse Mercator) try: utm_coords = utm.from_latlon(lat, lon) results['UTM'] = { 'formatted': f"{utm_coords[2]}{'N' if lat >= 0 else 'S'} {utm_coords[0]:.1f}E {utm_coords[1]:.1f}N", 'components': { 'easting': utm_coords[0], 'northing': utm_coords[1], 'zone_number': utm_coords[2], 'zone_letter': utm_coords[3] } } except: results['UTM'] = {'error': 'UTM conversion failed'} # MGRS (Military Grid Reference System) try: m = mgrs.MGRS() mgrs_coord = m.toMGRS(lat, lon) results['MGRS'] = { 'formatted': mgrs_coord, 'components': { 'full_coord': mgrs_coord } } except: results['MGRS'] = {'error': 'MGRS conversion failed'} return results if format_type == 'all' else results.get(format_type.upper(), {}) def format_coordinate_response(self, results: dict) -> str: """Format coordinate conversion results""" output = "[Coordinate Analysis]\n" output += "═" * 50 + "\n\n" for format_type, data in results.items(): output += f"[{format_type}]\n" if 'error' in data: output += f"Error: {data['error']}\n" else: output += f"Formatted: {data['formatted']}\n" output += "Components:\n" for key, value in data['components'].items(): output += f" {key}: {value}\n" output += "-" * 30 + "\n" return output def generate_response(self, user_input: str, current_coords: Tuple[float, float]) -> str: try: # Enhanced coordinate processing coords = self.parse_coordinates(user_input) if coords: if "convert" in user_input.lower(): results = self.format_coordinates(*coords) return self.format_coordinate_response(results) elif "distance" in user_input.lower(): # Example: Calculate distance from current_coords to provided coords distance = self.calculate_distance(current_coords, coords) return f"The distance from your current location to the provided coordinates is approximately {distance:.2f} kilometers." # Regular analysis processing messages = [ {"role": "system", "content": self.system_prompt}, {"role": "user", "content": user_input} ] response = self.client.chat.completions.create( messages=messages, model="claude-3.5-sonnet", stream=False ) return self.format_analytical_response(response.choices[0].message.content) except Exception as e: return self.format_error_response(str(e)) def calculate_distance(self, coord1: Tuple[float, float], coord2: Tuple[float, float]) -> float: """ Calculate the great-circle distance between two points using the Haversine formula Returns distance in kilometers """ from math import radians, sin, cos, sqrt, atan2 lat1, lon1 = coord1 lat2, lon2 = coord2 R = 6371.0 # Radius of the Earth in km dlat = radians(lat2 - lat1) dlon = radians(lon2 - lon1) a = sin(dlat / 2)**2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c return distance def format_analytical_response(self, content: str) -> str: """Format regular analytical responses""" return content def format_error_response(self, error: str) -> str: """Format error messages""" return f"Error: {error}" def main(): app = AnalyticalInterface() app.geometry("1000x700") app.mainloop() if __name__ == "__main__": main()Detailed Enhancements Explained
-
Real-Time Geographical Updates:
-
Live Coordinate Tracking:
- Added a background thread (
update_coordinates_loop) that simulates receiving new geographical coordinates every 10 seconds. This simulates real-time data; you can replace the random coordinate generation with actual data sources such as GPS readings or an external API. - The current coordinates are stored in
self.current_coords.
- Added a background thread (
-
Map Integration:
- Integrated the
foliumlibrary to generate an interactive map (self.map) that displays the current location. - The map is saved as
map.htmland automatically opened in the user's default web browser. - The
update_mapmethod updates the map with the new coordinates.
- Integrated the
-
-
Enhanced Waifu Persona for Athena:
-
Refined Persona:
- Updated the
system_promptto provide Athena with a more sophisticated waifu persona. The prompt now balances analytical capabilities with gentle cultural expressions, ensuring responses are both precise and warmly engaging.
- Updated the
-
Avatar Display:
- Incorporated an avatar image (
athena_avatar.png) to visually represent Athena. Ensure you have an image namedathena_avatar.pngin the same directory as your script. - The avatar is displayed within the chat interface to enhance the waifu experience.
- Incorporated an avatar image (
-
Cultural Expressions:
- Modified response formatting to include subtle Japanese expressions, enhancing the cultural integration aspect of Athena's persona.
-
-
UI Enhancements:
-
Tabbed Interface:
- Utilized
ttk.Notebookto create a tabbed interface separating Chat and Live Map functionalities. This organization improves user experience by categorizing features.
- Utilized
-
Responsive Design:
- Adjusted the window size to
1000x700for better visibility and usability. - Enhanced layout within tabs for a cleaner and more intuitive interface.
- Adjusted the window size to
-
-
Additional Functionalities:
-
Distance Calculation:
- Added the capability to calculate the distance between the current live coordinates and user-provided coordinates using the Haversine formula. Users can input queries like "Calculate distance to [coordinates]."
-
Error Handling:
- Improved error handling to provide more informative messages to the user in case of failures.
-
Running the Application
-
Ensure Dependencies are Installed: Make sure you have all the required libraries installed. You can install any missing libraries using
pip:pip install g4f utm mgrs folium pillow -
Add Athena's Avatar:
- Place an image named
athena_avatar.pngin the same directory as your Python script. This image represents Athena in the chat interface. - The avatar enhances the waifu experience by providing a visual representation of Athena.
- Place an image named
-
Execute the Script: Run the Python script:
python your_script_name.py -
Interact with Athena:
- Navigate between the Chat and Live Map tabs.
- In the Chat tab, interact with Athena by typing queries or commands.
- Observe real-time geographical updates in the Live Map tab as the application simulates coordinate changes.
Conclusion
These enhancements transform your application into a more dynamic and engaging tool. Athena now not only provides analytical insights but also offers a charming waifu interaction complemented by live geographical data visualization. Feel free to adapt and expand upon these features to suit your specific needs!
-