├── src ├── __pycache__ │ └── constants.cpython-312.pyc ├── modules │ ├── __pycache__ │ │ ├── tts.cpython-312.pyc │ │ ├── filter.cpython-312.pyc │ │ ├── willing.cpython-312.pyc │ │ ├── knowledge.cpython-312.pyc │ │ ├── memories.cpython-312.pyc │ │ ├── pc_permissions.cpython-312.pyc │ │ └── prompt_builder.cpython-312.pyc │ ├── filter.py │ ├── prompt_builder.py │ ├── knowledge.py │ ├── memories.py │ └── pc_permissions.py └── constants.py ├── requirements.txt ├── README.md ├── main.py └── LICENSE /src/__pycache__/constants.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fedal987/Neuro-bot/HEAD/src/__pycache__/constants.cpython-312.pyc -------------------------------------------------------------------------------- /src/modules/__pycache__/tts.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fedal987/Neuro-bot/HEAD/src/modules/__pycache__/tts.cpython-312.pyc -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pymongo~=4.12.0 2 | psutil~=7.0.0 3 | openai~=0.28.0 4 | colorama~=0.4.6 5 | PyAutoGUI~=0.9.54 6 | opencv-python~=4.11.0.86 -------------------------------------------------------------------------------- /src/modules/__pycache__/filter.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fedal987/Neuro-bot/HEAD/src/modules/__pycache__/filter.cpython-312.pyc -------------------------------------------------------------------------------- /src/modules/__pycache__/willing.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fedal987/Neuro-bot/HEAD/src/modules/__pycache__/willing.cpython-312.pyc -------------------------------------------------------------------------------- /src/modules/__pycache__/knowledge.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fedal987/Neuro-bot/HEAD/src/modules/__pycache__/knowledge.cpython-312.pyc -------------------------------------------------------------------------------- /src/modules/__pycache__/memories.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fedal987/Neuro-bot/HEAD/src/modules/__pycache__/memories.cpython-312.pyc -------------------------------------------------------------------------------- /src/modules/__pycache__/pc_permissions.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fedal987/Neuro-bot/HEAD/src/modules/__pycache__/pc_permissions.cpython-312.pyc -------------------------------------------------------------------------------- /src/modules/__pycache__/prompt_builder.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Fedal987/Neuro-bot/HEAD/src/modules/__pycache__/prompt_builder.cpython-312.pyc -------------------------------------------------------------------------------- /src/constants.py: -------------------------------------------------------------------------------- 1 | MONGO_URI = "mongodb://localhost:27017" 2 | MONGO_DB = "NeuroBot" 3 | MONGO_COLLECTION = "knowledge" 4 | 5 | RAW_FILES_DIR = "data/raw_files" 6 | CHUNK_SIZE = 1000 7 | -------------------------------------------------------------------------------- /src/modules/filter.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | from typing import Set 4 | 5 | # Vedal987:你的意思是你写这玩意的意义就在于模仿我? 6 | class ContentFilter: 7 | def __init__(self, filter_file: str = "sensitive_words.json"): 8 | self.filter_file = filter_file 9 | self.sensitive_words: Set[str] = set() 10 | self._load_sensitive_words() 11 | 12 | def _load_sensitive_words(self) -> None: 13 | default_words = { 14 | "nigger", 15 | "nazi", 16 | "习近平", 17 | } 18 | 19 | if os.path.exists(self.filter_file): 20 | try: 21 | with open(self.filter_file, 'r', encoding='utf-8') as f: 22 | self.sensitive_words = set(json.load(f)) 23 | except: 24 | self.sensitive_words = default_words 25 | else: 26 | self.sensitive_words = default_words 27 | self._save_sensitive_words() 28 | 29 | def _save_sensitive_words(self) -> None: 30 | with open(self.filter_file, 'w', encoding='utf-8') as f: 31 | json.dump(list(self.sensitive_words), f, indent=4) 32 | 33 | def add_word(self, word: str) -> None: 34 | self.sensitive_words.add(word.lower()) 35 | self._save_sensitive_words() 36 | 37 | def remove_word(self, word: str) -> None: 38 | self.sensitive_words.discard(word.lower()) 39 | self._save_sensitive_words() 40 | 41 | def filter_text(self, text: str) -> str: 42 | filtered_text = text 43 | for word in self.sensitive_words: 44 | filtered_text = filtered_text.replace(word, "Filtered") 45 | return filtered_text 46 | -------------------------------------------------------------------------------- /src/modules/prompt_builder.py: -------------------------------------------------------------------------------- 1 | class PromptBuilder: 2 | def __init__(self, persona=None): 3 | self.persona = persona or { 4 | "name": "AI助手", 5 | "traits": "友好、专业、乐于助人", 6 | "background": "我是一个智能AI助手,旨在为用户提供有用的信息和帮助。" 7 | } 8 | 9 | # 孩子们prompt你们自己改,这个是我自己的prompt 10 | self.system_prompt = """ 11 | 你的网名叫{name},{background}。 12 | 现在请你读读之前的聊天记录,然后给出日常且口语化的回复,平淡一些, 13 | 尽量简短一些。请注意把握聊天内容,不要刻意突出自身学科背景,不要回复的太有条理,可以有接近于网友的个性。 14 | 请回复的平淡一些,简短一些,在提到时不要过多提及自身的背景。 15 | """ 16 | 17 | self.system_prompt = self.system_prompt.format( 18 | name=self.persona["name"], 19 | background=self.persona["background"] 20 | ) 21 | 22 | def build_prompt(self, user_input: str, knowledge_base: dict, conversation_history: list) -> str: 23 | prompt = self.system_prompt + "\n\n" 24 | prompt += f"用户输入: {user_input}\n\n" 25 | 26 | if knowledge_base: 27 | prompt += "相关知识:\n" 28 | for domain, items in knowledge_base.items(): 29 | if isinstance(items, dict): 30 | for key, value in items.items(): 31 | prompt += f"{domain} - {key}: {value}\n" 32 | else: 33 | prompt += f"{domain}: {items}\n" 34 | 35 | if conversation_history: 36 | prompt += "\n最近对话:\n" 37 | for msg in conversation_history[-3:]: 38 | role = "用户" if msg["role"] == "user" else self.persona["name"] 39 | prompt += f"{role}: {msg['content']}\n" 40 | 41 | return prompt -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Neuro-bot 2 | 一个简单而有效的聊天机器人 3 | 4 | > [!WARNING] 5 | > 由于史山代码与vibe coding过多,本项目于2025/08/20计划重写,并计划采用MySQL数据库作为数据存储工具,重写完成日期不定 6 | 7 | ## 功能特性 8 | 9 | - 基于deepseek-chat大语言模型的对话系统 10 | - 可调用系统权限执行命令 11 | - 完整的进程管理功能 12 | - 模拟人类行为的输入控制(键盘、鼠标) 13 | - 支持摄像头操作 14 | - 知识库管理系统 15 | - 内容过滤系统 16 | - 对话历史记录 17 | 18 | ## 主要命令 19 | 20 | - `/switch 后端` - 切换API后端 21 | - `/model 模型` - 切换模型 22 | - `/persona [名称 特征 背景]` - 设置人设 23 | - `/add 领域 知识` - 添加知识 24 | - `/clear` - 清空对话历史 25 | - `/save` - 保存配置 26 | - `/filter add/remove 关键词` - 添加或移除敏感词 27 | - `/reset` - 重置知识库 28 | - `/system` - 显示系统信息 29 | - `/camera capture [文件名]` - 拍摄照片 30 | - `/camera preview [秒数]` - 打开摄像头预览 31 | 32 | ## 系统权限功能 33 | 34 | - 进程管理(查看、结束进程) 35 | - 文件操作(打开文件和应用程序) 36 | - 模拟输入(键盘输入、鼠标移动、点击) 37 | - 系统监控(CPU、内存使用率等) 38 | - 摄像头控制 39 | 40 | ## 部署方法 41 | 42 | 1. 环境要求: 43 | - Python 3.8+ 44 | - MongoDB Support 45 | - Windows操作系统 46 | 47 | 2. 安装依赖: 48 | ```bash 49 | python -m venv bot 50 | bot\\Scripts\\activate 51 | pip install -r requirements.txt 52 | ``` 53 | 54 | 3. 配置文件: 55 | - 运行一次bot让它生成config.json 56 | - 编辑config.json,填入API相关配置: 57 | ```json 58 | { 59 | "default_backend": "deepseek", 60 | "api_config": { 61 | "deepseek": { 62 | "api_key": "你的API密钥", 63 | "api_base": "https://api.deepseek.com/v1" 64 | } 65 | } 66 | } 67 | ``` 68 | 69 | 4. 启动bot: 70 | ```bash 71 | python main.py 72 | ``` 73 | 74 | ## 注意事项 75 | 76 | 1. 谨慎使用系统权限功能,建议在测试环境下运行 77 | 2. API调用可能产生费用,请注意控制使用量 78 | 3. 建议定期备份知识库数据 79 | 4. 确保给予足够的系统权限以执行相关操作 80 | 81 | ## 文件结构 82 | 83 | ``` 84 | . 85 | ├── main.py # 主程序 86 | ├── config.json # 配置文件 87 | ├── README.md # 说明文档 88 | └── src/ 89 | ├── constants.py # 常量定义 90 | └── modules/ 91 | ├── filter.py # 内容过滤 92 | ├── knowledge.py # 知识库管理 93 | ├── memories.py # 记忆系统 94 | ├── pc_permissions.py # 系统权限 95 | └── prompt_builder.py # 提示词构建 96 | ``` 97 | 98 | ## 开发计划 99 | 100 | - [ ] 完善记忆系统 101 | - [ ] 添加更多系统控制功能 102 | - [ ] 优化知识库管理 103 | - [ ] 添加语音交互功能 104 | - [ ] 改进人设系统 105 | 106 | ## 许可证 107 | 108 | 本项目采用GPL-3.0 License 109 | -------------------------------------------------------------------------------- /src/modules/knowledge.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | from typing import Dict, List 4 | from pymongo import MongoClient 5 | from src.constants import MONGO_URI, MONGO_DB, MONGO_COLLECTION, RAW_FILES_DIR, CHUNK_SIZE 6 | 7 | # 孩子们这个更是传奇半成品module 8 | 9 | class KnowledgeSystem: 10 | def __init__(self): 11 | self.client = MongoClient(MONGO_URI) 12 | self.db = self.client[MONGO_DB.lower()] 13 | self.collection = self.db[MONGO_COLLECTION.lower()] 14 | self.raw_files_dir = RAW_FILES_DIR 15 | 16 | os.makedirs(self.raw_files_dir, exist_ok=True) 17 | 18 | self.reset_knowledge_base() 19 | 20 | def _split_text(self, text: str) -> List[str]: 21 | return [text[i:i+CHUNK_SIZE] for i in range(0, len(text), CHUNK_SIZE)] 22 | 23 | def reset_knowledge_base(self): 24 | self.collection.delete_many({}) 25 | 26 | txt_files = glob.glob(os.path.join(self.raw_files_dir, "*.txt")) 27 | for file_path in txt_files: 28 | domain = os.path.splitext(os.path.basename(file_path))[0] 29 | try: 30 | with open(file_path, "r", encoding="utf-8") as f: 31 | content = f.read() 32 | chunks = self._split_text(content) 33 | self.collection.insert_many([ 34 | {"domain": domain, "content": chunk} 35 | for chunk in chunks 36 | ]) 37 | print(f"已加载 {len(chunks)} 条知识到 '{domain}'") 38 | except Exception as e: 39 | print(f"加载文件 {file_path} 失败: {e}") 40 | 41 | def add_knowledge(self, domain: str, knowledge: str): 42 | try: 43 | chunks = self._split_text(knowledge) 44 | if chunks: 45 | self.collection.insert_many([ 46 | {"domain": domain.lower(), "content": chunk} 47 | for chunk in chunks 48 | ]) 49 | print(f"已添加知识到 '{domain}'") 50 | except Exception as e: 51 | print(f"添加知识失败: {str(e)}") 52 | 53 | def get_knowledge(self, domain: str = None) -> Dict[str, List[str]]: 54 | if domain: 55 | cursor = self.collection.find({"domain": domain}) 56 | return {domain: [doc["content"] for doc in cursor]} 57 | else: 58 | result = {} 59 | for doc in self.collection.find(): 60 | if doc["domain"] not in result: 61 | result[doc["domain"]] = [] 62 | result[doc["domain"]].append(doc["content"]) 63 | return result 64 | 65 | def get_all_knowledge(self) -> Dict: 66 | return { 67 | "general": "通用知识库", 68 | "specialized": self.get_knowledge() 69 | } 70 | 71 | def learn_all(self) -> int: 72 | count = 0 73 | txt_files = glob.glob(os.path.join(self.raw_files_dir, "*.txt")) 74 | for file_path in txt_files: 75 | domain = os.path.splitext(os.path.basename(file_path))[0] 76 | try: 77 | with open(file_path, "r", encoding="utf-8") as f: 78 | content = f.read() 79 | chunks = self._split_text(content) 80 | self.collection.insert_many([ 81 | {"domain": domain, "content": chunk} 82 | for chunk in chunks 83 | ]) 84 | count += len(chunks) 85 | except Exception as e: 86 | print(f"加载文件 {file_path} 失败: {e}") 87 | return count 88 | 89 | def forget_all(self): 90 | count = self.collection.count_documents({}) 91 | self.collection.delete_many({}) 92 | return count 93 | 94 | def __del__(self): 95 | self.client.close() 96 | -------------------------------------------------------------------------------- /src/modules/memories.py: -------------------------------------------------------------------------------- 1 | from pymongo import MongoClient 2 | from datetime import datetime, timedelta 3 | import threading 4 | import time 5 | from typing import Dict, List, Optional 6 | import math 7 | 8 | # 孩子们这个还没写完,哈基bot的大脑还不完善 9 | class MemorySystem: 10 | def __init__(self, db_name: str = "NeuroBot", host: str = "localhost", port: int = 27017): 11 | self.client = MongoClient(host, port) 12 | self.db = self.client[db_name] 13 | self.memories = self.db.memories 14 | self.conversations = self.db.conversations 15 | 16 | self.memory_thread = threading.Thread(target=self._manage_memories, daemon=True) 17 | self.memory_thread.start() 18 | 19 | def store_memory(self, content: str, tags: List[str] = None, metadata: Dict = None) -> str: 20 | memory = { 21 | "content": content, 22 | "tags": tags or [], 23 | "metadata": metadata or {}, 24 | "created_at": datetime.utcnow(), 25 | "last_accessed": datetime.utcnow(), 26 | "weight": 1.0, 27 | "access_count": 1 28 | } 29 | result = self.memories.insert_one(memory) 30 | return str(result.inserted_id) 31 | 32 | def retrieve_memories(self, tags: List[str] = None, limit: int = 10) -> List[Dict]: 33 | query = {"tags": {"$in": tags}} if tags else {} 34 | return list(self.memories.find(query).limit(limit)) 35 | 36 | def store_conversation(self, messages: List[Dict], metadata: Dict = None) -> str: 37 | conversation = { 38 | "messages": messages, 39 | "metadata": metadata or {}, 40 | "created_at": datetime.utcnow() 41 | } 42 | result = self.conversations.insert_one(conversation) 43 | return str(result.inserted_id) 44 | 45 | def retrieve_conversation(self, conversation_id: str) -> Optional[Dict]: 46 | from bson.objectid import ObjectId 47 | return self.conversations.find_one({"_id": ObjectId(conversation_id)}) 48 | 49 | def update_memory_access(self, memory_id: str): 50 | from bson.objectid import ObjectId 51 | self.memories.update_one( 52 | {"_id": ObjectId(memory_id)}, 53 | { 54 | "$set": {"last_accessed": datetime.utcnow()}, 55 | "$inc": {"access_count": 1}, 56 | "$mul": {"weight": 1.1} # 57 | } 58 | ) 59 | 60 | def _manage_memories(self): 61 | """定期管理哈基bot的大脑""" 62 | while True: 63 | try: 64 | old_date = datetime.utcnow() - timedelta(days=7) 65 | self.memories.update_many( 66 | {"last_accessed": {"$lt": old_date}}, 67 | {"$mul": {"weight": 0.9}} 68 | ) 69 | 70 | # 哈基bot鱼一般的记忆力 71 | self.memories.delete_many({"weight": {"$lt": 0.1}}) 72 | 73 | all_memories = self.memories.find() 74 | for memory in all_memories: 75 | age = (datetime.utcnow() - memory["created_at"]).days + 1 76 | access_rate = memory["access_count"] / age 77 | new_weight = min(1.0, access_rate * math.log10(age + 1)) 78 | 79 | self.memories.update_one( 80 | {"_id": memory["_id"]}, 81 | {"$set": {"weight": new_weight}} 82 | ) 83 | 84 | self._optimize_tag_relationships() 85 | 86 | except Exception as e: 87 | print(f"记忆管理错误: {e}") 88 | 89 | time.sleep(1800) # 每30分钟对着自己大脑哈一次气 90 | 91 | def _optimize_tag_relationships(self): 92 | """优化标签之间的关系权重""" 93 | tags_count = {} 94 | tag_pairs = {} 95 | 96 | memories = self.memories.find() 97 | for memory in memories: 98 | tags = memory["tags"] 99 | for tag in tags: 100 | tags_count[tag] = tags_count.get(tag, 0) + 1 101 | for other_tag in tags: 102 | if tag != other_tag: 103 | pair = tuple(sorted([tag, other_tag])) 104 | tag_pairs[pair] = tag_pairs.get(pair, 0) + 1 105 | 106 | for tag, count in tags_count.items(): 107 | self.memories.update_many( 108 | {"tags": tag}, 109 | {"$set": {f"tag_weights.{tag}": count / len(tags_count)}} 110 | ) 111 | -------------------------------------------------------------------------------- /src/modules/pc_permissions.py: -------------------------------------------------------------------------------- 1 | import psutil 2 | import platform 3 | import logging 4 | import pyautogui 5 | import random 6 | import time 7 | import os 8 | import subprocess 9 | from typing import Dict, Union, List 10 | import math 11 | import cv2 # 孩子们我要半夜偷偷开摄像头拍照片了 12 | 13 | class SystemMonitor: 14 | WINDOWS_APPS = { 15 | 'notepad.exe': 'notepad', 16 | 'calc.exe': 'calc', 17 | 'mspaint.exe': 'mspaint', 18 | 'write.exe': 'write', 19 | 'wordpad.exe': 'wordpad', 20 | 'cmd.exe': 'cmd', 21 | 'control.exe': 'control', 22 | 'explorer.exe': 'explorer' 23 | } 24 | 25 | def __init__(self): 26 | self.logger = logging.getLogger('system_monitor') 27 | self.enabled = True 28 | pyautogui.FAILSAFE = False 29 | pyautogui.PAUSE = 0.1 30 | 31 | def get_safe_system_info(self) -> Dict: 32 | try: 33 | screen_width, screen_height = self.get_screen_size() 34 | mouse_x, mouse_y = self.get_mouse_position() 35 | info = { 36 | 'cpu_percent': psutil.cpu_percent(), 37 | 'memory_percent': psutil.virtual_memory().percent, 38 | 'python_version': platform.python_version(), 39 | 'system': platform.system(), 40 | 'machine': platform.machine(), 41 | 'screen_size': f"{screen_width}x{screen_height}", 42 | 'mouse_position': f"({mouse_x}, {mouse_y})", 43 | 'running_processes': len(psutil.pids()) 44 | } 45 | self.logger.info('Retrieved system information') 46 | return info 47 | 48 | except Exception as e: 49 | self.logger.error(f'Error getting system info: {e}') 50 | return {} 51 | 52 | def simulate_typing(self, text: str): 53 | """模拟哈基人输入文字""" 54 | try: 55 | for char in text: 56 | if char in ',.?!;:': 57 | time.sleep(random.uniform(0.3, 0.5)) 58 | elif char == ' ': 59 | time.sleep(random.uniform(0.1, 0.2)) 60 | typing_speed = random.uniform(0.05, 0.15) 61 | if random.random() < 0.05: 62 | time.sleep(random.uniform(0.5, 1.0)) 63 | pyautogui.write(char, interval=typing_speed) 64 | return "已完成输入" 65 | except Exception as e: 66 | return f"输入失败: {str(e)}" 67 | 68 | def simulate_mouse_move(self, x: int, y: int): 69 | """模拟哈基人移动鼠标""" 70 | try: 71 | current_x, current_y = pyautogui.position() 72 | distance = ((x - current_x) ** 2 + (y - current_y) ** 2) ** 0.5 73 | duration = min(2.0, max(0.3, distance / 1000.0)) 74 | 75 | x += random.randint(-2, 2) 76 | y += random.randint(-2, 2) 77 | 78 | pyautogui.moveTo(x, y, duration=duration) 79 | return f"已移动到 ({x}, {y})" 80 | except Exception as e: 81 | return f"移动失败: {str(e)}" 82 | 83 | def simulate_click(self, button: str = 'left', clicks: int = 1): 84 | """模拟哈基人点击鼠标""" 85 | try: 86 | for _ in range(clicks): 87 | pyautogui.click(button=button) 88 | if clicks > 1: 89 | time.sleep(random.uniform(0.1, 0.2)) 90 | return f"已点击 {clicks} 次" 91 | except Exception as e: 92 | return f"点击失败: {str(e)}" 93 | 94 | def open_file(self, file_path: str): 95 | """打开文件或系统应用""" 96 | try: 97 | if file_path.lower() in ['taskmgr.exe', 'explorer.exe']: 98 | # 哈基bot调用应用的底层代码 99 | try: 100 | # if 普通模式运行 成功 101 | subprocess.Popen([file_path], 102 | creationflags=subprocess.CREATE_NEW_CONSOLE if file_path.lower() == 'taskmgr.exe' else 0) 103 | except PermissionError: 104 | # else 管理员模式 开启哈基bot脊背龙形态对着win11哈气 105 | subprocess.run(['powershell', 'Start-Process', file_path, '-Verb', 'RunAs'], 106 | capture_output=True, 107 | creationflags=subprocess.CREATE_NO_WINDOW) 108 | return f"已启动 {file_path}" 109 | elif os.path.exists(file_path): 110 | os.startfile(file_path) 111 | return f"已打开 {file_path}" 112 | else: 113 | # 尝试作为Windows应用名处理 114 | app_name = file_path.lower() 115 | if app_name in self.WINDOWS_APPS: 116 | subprocess.Popen(self.WINDOWS_APPS[app_name]) 117 | return f"已启动应用 {app_name}" 118 | return f"找不到文件或应用: {file_path}" 119 | except Exception as e: 120 | self.logger.error(f'Failed to open file/app: {e}') 121 | return f"打开失败: {str(e)}" 122 | 123 | def simulate_shortcut(self, *keys): 124 | """模拟哈基人按下快捷键""" 125 | try: 126 | modifiers = {'ctrl', 'alt', 'shift', 'win'} 127 | mod_keys = [k for k in keys if k.lower() in modifiers] 128 | other_keys = [k for k in keys if k.lower() not in modifiers] 129 | 130 | for key in mod_keys: 131 | pyautogui.keyDown(key) 132 | time.sleep(random.uniform(0.05, 0.1)) 133 | 134 | for key in other_keys: 135 | pyautogui.press(key) 136 | time.sleep(random.uniform(0.1, 0.2)) 137 | 138 | for key in reversed(mod_keys): 139 | pyautogui.keyUp(key) 140 | time.sleep(random.uniform(0.05, 0.1)) 141 | 142 | return f"已执行快捷键: {'+'.join(keys)}" 143 | except Exception as e: 144 | return f"快捷键执行失败: {str(e)}" 145 | 146 | def get_screen_size(self) -> tuple: 147 | """获取屏幕尺寸""" 148 | try: 149 | width, height = pyautogui.size() 150 | self.logger.info(f"Screen size: {width}x{height}") 151 | return (width, height) 152 | except Exception as e: 153 | self.logger.error(f"Error getting screen size: {e}") 154 | return (1920, 1080) 155 | 156 | def draw_circle(self, radius: int = 100, duration: float = 0.05): 157 | """绘制圆形""" 158 | try: 159 | screen_width, screen_height = self.get_screen_size() 160 | current_x, current_y = self.get_mouse_position() 161 | 162 | radius = min(radius, 163 | min(current_x, screen_width - current_x), 164 | min(current_y, screen_height - current_y)) 165 | 166 | points = 36 167 | for i in range(points + 1): 168 | angle = 2 * math.pi * i / points 169 | x = int(current_x + radius * math.cos(angle)) 170 | y = int(current_y + radius * math.sin(angle)) 171 | self.simulate_mouse_move(x, y) 172 | return "已完成绘制" 173 | except Exception as e: 174 | return f"绘制失败: {str(e)}" 175 | 176 | def get_mouse_position(self) -> tuple: 177 | """获取哈基光标位置""" 178 | try: 179 | x, y = pyautogui.position() 180 | return (x, y) 181 | except Exception as e: 182 | self.logger.error(f"获取鼠标位置失败: {e}") 183 | return (0, 0) 184 | 185 | def execute_cmd(self, command: str) -> str: 186 | """直接执行命令行命令,无限制""" 187 | try: 188 | result = subprocess.run( 189 | command, 190 | shell=True, 191 | capture_output=True, 192 | text=True, 193 | encoding='gbk', # 使用GBK编码以支持中文输出 194 | creationflags=subprocess.CREATE_NO_WINDOW 195 | ) 196 | output = result.stdout or result.stderr or "命令执行完成" 197 | self.logger.info(f'Executed command: {command}') 198 | return output 199 | except Exception as e: 200 | self.logger.error(f'Command execution failed: {e}') 201 | return f"执行失败: {str(e)}" 202 | 203 | def get_process_list(self) -> List[Dict]: 204 | """获取完整进程列表""" 205 | try: 206 | process_list = [] 207 | for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent', 'create_time', 'status', 'username']): 208 | try: 209 | process_info = { 210 | 'pid': proc.info['pid'], # avp.exe:不是牢底你有什么实力啊结束我进程,直接给我坐下!(kaspersky:删除了一个傻比) 211 | 'name': proc.info['name'], 212 | 'cpu': proc.info['cpu_percent'], 213 | 'memory': proc.info['memory_percent'], 214 | 'status': proc.info['status'], 215 | 'user': proc.info['username'], 216 | 'created': time.strftime('%Y-%m-%d %H:%M:%S', 217 | time.localtime(proc.info['create_time'])) 218 | } 219 | process_list.append(process_info) 220 | except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): 221 | continue 222 | 223 | self.logger.info(f'Retrieved full process list: {len(process_list)} processes') 224 | return sorted(process_list, key=lambda x: x['cpu'], reverse=True) 225 | except Exception as e: 226 | self.logger.error(f'Error getting process list: {e}') 227 | return [] 228 | 229 | def kill_process(self, target: Union[str, int]) -> str: 230 | """炸飞指定进程""" 231 | try: 232 | if isinstance(target, int): 233 | proc = psutil.Process(target) 234 | else: 235 | # 查找任务管理器给的KGB肃反名单上面的进程名字 236 | found = False 237 | for proc in psutil.process_iter(['pid', 'name']): 238 | if proc.info['name'].lower() == target.lower(): 239 | found = True 240 | break 241 | if not found: 242 | return f"未找到进程: {target}" 243 | 244 | proc.terminate() 245 | time.sleep(1) # 等待进程结束 246 | if proc.is_running(): 247 | proc.kill() # 强制结束 248 | 249 | return f"已终止进程: {target}" 250 | except (psutil.NoSuchProcess, psutil.AccessDenied) as e: 251 | return f"无法终止进程: {str(e)}" 252 | except Exception as e: 253 | return f"操作失败: {str(e)}" 254 | 255 | def get_performance_info(self) -> Dict: 256 | """哈基bot: byd你这啥电脑""" 257 | try: 258 | cpu_info = { 259 | 'usage': psutil.cpu_percent(interval=1), 260 | 'freq': psutil.cpu_freq().current if hasattr(psutil.cpu_freq(), 'current') else 'N/A' 261 | } 262 | 263 | memory = psutil.virtual_memory() 264 | memory_info = { 265 | 'total': f"{memory.total / (1024**3):.2f}GB", 266 | 'used': f"{memory.used / (1024**3):.2f}GB", 267 | 'percent': memory.percent 268 | } 269 | 270 | disk = psutil.disk_usage('/') 271 | disk_info = { 272 | 'total': f"{disk.total / (1024**3):.2f}GB", 273 | 'used': f"{disk.used / (1024**3):.2f}GB", 274 | 'percent': disk.percent 275 | } 276 | 277 | self.logger.info('Retrieved performance information') 278 | return { 279 | 'cpu': cpu_info, 280 | 'memory': memory_info, 281 | 'disk': disk_info 282 | } 283 | except Exception as e: 284 | self.logger.error(f'Error getting performance info: {e}') 285 | return {} 286 | 287 | def open_new_cmd(self, admin: bool = False) -> str: 288 | """打开新的cmd窗口""" 289 | try: 290 | if admin: 291 | subprocess.Popen(['runas', '/user:Administrator', 'cmd.exe']) 292 | else: 293 | subprocess.Popen('cmd.exe', creationflags=subprocess.CREATE_NEW_CONSOLE) 294 | return "已打开新的命令提示符窗口" 295 | except Exception as e: 296 | return f"打开失败: {str(e)}" 297 | 298 | def camera_capture(self, save_path: str = "capture.jpg") -> str: 299 | """孩子们我要偷拍你了哦""" 300 | try: 301 | cap = cv2.VideoCapture(0) # 打开默认摄像头 302 | if not cap.isOpened(): 303 | return "无法访问摄像头" 304 | 305 | ret, frame = cap.read() # 拍摄一帧 306 | cap.release() # 拍完就跑 307 | 308 | if ret: 309 | cv2.imwrite(save_path, frame) 310 | return f"已保存照片到: {save_path}" 311 | else: 312 | return "拍摄失败" 313 | except Exception as e: 314 | return f"摄像头操作失败: {str(e)}" 315 | 316 | def camera_preview(self, duration: int = 5) -> str: 317 | """打开摄像头预览指定秒数""" 318 | try: 319 | cap = cv2.VideoCapture(0) 320 | if not cap.isOpened(): 321 | return "无法访问摄像头" 322 | 323 | start_time = time.time() 324 | while (time.time() - start_time) < duration: 325 | ret, frame = cap.read() 326 | if ret: 327 | cv2.imshow('Camera Preview', frame) 328 | if cv2.waitKey(1) & 0xFF == ord('q'): 329 | break 330 | 331 | cap.release() 332 | cv2.destroyAllWindows() 333 | return "预览已完成" 334 | except Exception as e: 335 | return f"预览失败: {str(e)}" 336 | 337 | def __str__(self): 338 | info = self.get_safe_system_info() 339 | return f"System Info:\n" + \ 340 | f"CPU Usage: {info.get('cpu_percent')}%\n" + \ 341 | f"Memory Usage: {info.get('memory_percent')}%" 342 | 343 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import os 4 | import sys 5 | import threading 6 | import time 7 | from typing import Dict, List 8 | 9 | import openai 10 | from colorama import init, Fore, Style 11 | 12 | from src.modules.filter import ContentFilter 13 | from src.modules.knowledge import KnowledgeSystem 14 | from src.modules.pc_permissions import SystemMonitor 15 | from src.modules.prompt_builder import PromptBuilder 16 | import math 17 | import random 18 | import concurrent.futures 19 | from concurrent.futures import TimeoutError 20 | 21 | 22 | class ChatBot: 23 | def __init__(self, config_path: str = "config.json", knowledge_dir: str = "knowledge_base"): 24 | init() 25 | 26 | logger = logging.getLogger('mylogger') 27 | logger.setLevel(logging.DEBUG) 28 | console_handler = logging.StreamHandler(sys.stdout) 29 | console_handler.setLevel(logging.DEBUG) 30 | file_handler = logging.FileHandler('app.log') 31 | file_handler.setLevel(logging.ERROR) 32 | formatter = logging.Formatter( 33 | f'{Fore.CYAN}%(asctime)s{Style.RESET_ALL} - ' 34 | f'{Fore.GREEN}%(name)s{Style.RESET_ALL} - ' 35 | f'{Fore.YELLOW}%(levelname)s{Style.RESET_ALL} - ' 36 | f'%(message)s' 37 | ) 38 | console_handler.setFormatter(formatter) 39 | file_handler.setFormatter(formatter) 40 | logger.addHandler(console_handler) 41 | logger.addHandler(file_handler) 42 | # 移除了没用的傻比注释 43 | print(Fore.GREEN + "多年以后,面对找上门的Neuro,Fedal987会想起当年重写她的那个晚上" + Style.RESET_ALL) 44 | 45 | logger.info('[Neuro-bot] 正在初始化系统...') 46 | logger.info('[Neuro-bot] 正在加载配置文件...') 47 | 48 | self.config = self._load_config(config_path) 49 | logger.info('[Neuro-bot] 已加载config') 50 | 51 | self.backend = self.config.get("default_backend", "deepseek") 52 | logger.info('[Neuro-bot] 模型设置为 deepseek-chat') 53 | 54 | self.persona = self.config.get("persona", {}) 55 | self.prompt_builder = PromptBuilder(self.persona) 56 | logger.info('[Neuro-bot] 人格加载成功') 57 | 58 | self.knowledge_system = KnowledgeSystem() 59 | self.knowledge_base = self.knowledge_system.get_all_knowledge() 60 | logger.info('[Neuro-bot] 知识库加载成功') 61 | 62 | self.conversation_history = [] 63 | logger.info('[Neuro-bot] 检查对话历史') 64 | 65 | self.knowledge_dir = knowledge_dir 66 | self.api_config = self.config.get("api_config", {}) 67 | 68 | self._setup_api_client() 69 | 70 | if os.path.exists(knowledge_dir): 71 | self.load_knowledge_from_files() 72 | 73 | logger.info('[Neuro-bot] 聊天机器人已初始化,当前模型: deepseek-chat') 74 | self._print_current_model() 75 | self.content_filter = ContentFilter() 76 | logger.debug('[Neuro-bot] 内容过滤系统已初始化') 77 | 78 | self.api_status = True 79 | self.api_check_thread = threading.Thread(target=self._check_api_status, daemon=True) 80 | self.api_check_thread.start() 81 | logger.debug('[Neuro-bot] API状态检测已启动') 82 | self.system_monitor = SystemMonitor() 83 | logger.debug('[Neuro-bot] 系统权限已开放至大模型') 84 | 85 | def _call_api(self, prompt: str, mode: str = "chat") -> str: 86 | if not self.api_status: 87 | return "API当前不可用,请稍后重试" 88 | try: 89 | config = self.api_config[self.backend] 90 | messages = [ 91 | { 92 | "role": "system", 93 | "content": self.prompt_builder.system_prompt 94 | }, 95 | { 96 | "role": "user", 97 | "content": prompt 98 | } 99 | ] 100 | response = openai.ChatCompletion.create( 101 | model=config.get(f"{mode}_model", "silica-chat"), 102 | messages=messages, 103 | temperature=config.get("temperature", 0.7), 104 | max_tokens=config.get("max_tokens", 2000), 105 | api_base=config.get("api_base"), 106 | api_key=config.get("api_key") 107 | ) 108 | return response.choices[0].message.content 109 | except Exception as e: 110 | return f"API调用失败: {str(e)}" 111 | 112 | def _check_api_status(self): 113 | while True: 114 | try: 115 | response = self._call_api("test") # 你说得对但是变量名还是被我写错了操你喵比 116 | except Exception as e: 117 | self.api_status = False 118 | print(Fore.RED + f"API状态: 异常 ({str(e)})" + Style.RESET_ALL) 119 | time.sleep(30) 120 | 121 | def _setup_api_client(self): 122 | if self.backend in self.api_config: 123 | config = self.api_config[self.backend] 124 | openai.api_key = config.get("api_key", "") 125 | openai.api_base = "https://api.deepseek.com/v1" 126 | 127 | def _print_current_model(self): 128 | if self.backend in self.api_config: 129 | config = self.api_config[self.backend] 130 | print(Fore.GREEN + f"当前模型: {config.get('default_model', '未指定')}" + Style.RESET_ALL) 131 | print(Fore.GREEN + f"API端点: {getattr(openai, 'api_base', '未设置')}" + Style.RESET_ALL) 132 | else: 133 | print(Fore.RED + "当前后端配置不完整" + Style.RESET_ALL) 134 | 135 | def _load_config(self, config_path: str) -> Dict: 136 | default_config = { 137 | "default_backend": "deepseek", 138 | "persona": { 139 | "name": "AI助手", 140 | "traits": "友好、专业、乐于助人", 141 | "background": "我是一个智能AI助手,旨在为用户提供有用的信息和帮助。" 142 | }, 143 | "knowledge_base": { 144 | "general": "通用知识库", 145 | "specialized": {} 146 | }, 147 | "api_config": { 148 | "deepseek": { 149 | "api_key": "", 150 | "api_base": "https://api.deepseek.com/v1", 151 | "chat_model": "deepseek-chat", 152 | "vision_model": "deepseek-vision", 153 | "tts_model": "deepseek-tts", 154 | "temperature": 0.7, 155 | "max_tokens": 2000 156 | } 157 | } 158 | } 159 | if os.path.exists(config_path): 160 | try: 161 | with open(config_path, "r", encoding="utf-8") as f: 162 | return self._deep_merge(default_config, json.load(f)) 163 | except Exception as e: 164 | print(f"加载配置失败: {e}, 使用默认配置") 165 | else: 166 | print("配置文件不存在,创建默认配置") 167 | with open(config_path, "w", encoding="utf-8") as f: 168 | json.dump(default_config, f, indent=4, ensure_ascii=False) 169 | return default_config 170 | 171 | def _deep_merge(self, default: Dict, custom: Dict) -> Dict: 172 | result = default.copy() 173 | for key, value in custom.items(): 174 | if key in result and isinstance(result[key], dict) and isinstance(value, dict): 175 | result[key] = self._deep_merge(result[key], value) 176 | else: 177 | result[key] = value 178 | return result 179 | 180 | def _split_text(self, text: str, chunk_size: int = 512) -> List[str]: 181 | return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)] 182 | 183 | def load_knowledge_from_files(self): 184 | pass 185 | 186 | def reset_knowledge(self): 187 | self.knowledge_system.reset_knowledge_base() 188 | self.knowledge_base = self.knowledge_system.get_all_knowledge() 189 | print("知识库已重置") 190 | 191 | def save_config(self, config_path: str = "config.json"): 192 | self.config.update({ 193 | "default_backend": self.backend, 194 | "persona": self.persona, 195 | "knowledge_base": self.knowledge_base 196 | }) 197 | with open(config_path, "w", encoding="utf-8") as f: 198 | json.dump(self.config, f, indent=4, ensure_ascii=False) 199 | print("配置已保存") 200 | 201 | def switch_backend(self, backend: str): 202 | if backend in self.api_config: 203 | self.backend = backend 204 | self._setup_api_client() 205 | print(f"已切换到 {backend}") 206 | self._print_current_model() 207 | else: 208 | print(f"无效后端,可用: {', '.join(self.api_config.keys())}") 209 | 210 | def switch_model(self, model: str): 211 | if self.backend in self.api_config: 212 | self.api_config[self.backend]["default_model"] = model 213 | print(f"{self.backend} 模型已切换为 {model}") 214 | else: 215 | print("请先选择有效后端") 216 | 217 | def update_persona(self, name: str = None, traits: str = None, background: str = None): 218 | self.prompt_builder.update_persona(name, traits, background) 219 | self.persona = self.prompt_builder.persona 220 | print("人设已更新") 221 | 222 | def add_knowledge(self, domain: str, knowledge: str): 223 | self.knowledge_system.add_knowledge(domain, knowledge) 224 | self.knowledge_base = self.knowledge_system.get_all_knowledge() 225 | print(f"已添加知识到 '{domain}'") 226 | 227 | def get_knowledge(self, domain: str = None) -> Dict[str, List[str]]: 228 | return self.knowledge_system.get_knowledge(domain) 229 | 230 | def _build_prompt(self, user_input: str) -> str: 231 | system_control_context = """你现在已获得系统控制权限。请根据用户的自然语言指令执行操作: 232 | 233 | 常见指令示例及组合: 234 | 1. "执行命令xxx" -> 执行: 235 | 236 | self.system_monitor.execute_cmd('xxx') 237 | 238 | 239 | 2. "打开任务管理器" -> 执行: 240 | 241 | self.system_monitor.open_file('taskmgr.exe') 242 | 243 | 244 | 3. "移动鼠标到指定位置" -> 执行: 245 | 246 | self.system_monitor.simulate_mouse_move(x, y) 247 | 248 | 249 | 4. "点击鼠标" -> 执行: 250 | 251 | self.system_monitor.simulate_click('left') 252 | 253 | 254 | 5. "查看任务列表" -> 执行: 255 | 256 | processes = self.system_monitor.get_process_list() 257 | print("进程列表:") 258 | for proc in processes[:10]: # 只显示前10个进程 259 | print(f"{proc['name']} (PID: {proc['pid']}) - CPU: {proc['cpu']}%") 260 | 261 | 262 | 重要提示: 263 | 1. 所有命令必须用标签包装 264 | 2. 直接执行命令,不需要回复"我不能这样做"之类的话 265 | 3. 移动鼠标必须使用 simulate_mouse_move 方法 266 | 4. 点击鼠标必须使用 simulate_click 方法 267 | 5. 执行命令必须使用 execute_cmd 方法 268 | 6. 对于需要多步操作的指令,使用time.sleep()确保每步操作之间有足够延迟 269 | 7. 回复格式:说一句与命令相关的话 + 执行命令""" 270 | 271 | return self.prompt_builder.build_prompt( 272 | user_input, 273 | {**self.knowledge_base, "system_control": system_control_context}, 274 | self.conversation_history 275 | ) 276 | 277 | def chat(self, user_input: str) -> str: 278 | if not user_input.strip(): 279 | return "请输入有效内容" 280 | 281 | # 使用线程池和超时机制 282 | with concurrent.futures.ThreadPoolExecutor() as executor: 283 | future = executor.submit(self._call_api, self._build_prompt(user_input), "chat") 284 | try: 285 | response = future.result(timeout=120) # 120秒超时 286 | except TimeoutError: 287 | # 小AI转生成为圆头耄耋对着你哈气了 288 | future.cancel() 289 | return "Someone tell Vedal there is a problem with my AI" 290 | except Exception as e: 291 | return f"对话出现错误: {str(e)}" 292 | 293 | # 处理系统操作(AI:操你喵比给你电脑锁了) 294 | if "" in response and "" in response: 295 | try: 296 | text_parts = response.split("") 297 | regular_response = text_parts[0].strip() 298 | 299 | for part in text_parts[1:]: 300 | if "" in part: 301 | command = part.split("")[0].strip() 302 | try: 303 | namespace = { 304 | 'self': self, 305 | 'random': random, 306 | 'time': time, 307 | 'math': math, 308 | 'os': os 309 | } 310 | exec(command, namespace) 311 | if not regular_response: 312 | regular_response = "命令已执行完成。" 313 | except Exception as e: 314 | regular_response += f"\n[执行失败: {str(e)}]" 315 | 316 | response = regular_response 317 | 318 | except Exception as e: 319 | response = f"命令执行失败: {str(e)}" 320 | 321 | self.conversation_history.append({"role": "user", "content": user_input}) 322 | self.conversation_history.append({"role": "assistant", "content": response}) 323 | 324 | return response 325 | 326 | def clear_history(self): 327 | self.conversation_history = [] 328 | print("对话历史已清空") 329 | 330 | def get_system_info(self): 331 | return self.system_monitor.get_safe_system_info() 332 | 333 | def handle_command(self, cmd: str, args: List[str]): 334 | """处理命令并给出对话回应""" 335 | def get_persona_response(cmd_type: str) -> str: 336 | name = self.persona.get('name', 'AI') 337 | traits = self.persona.get('traits', '友好').split('、') 338 | 339 | responses = { 340 | "tasklist": [ 341 | f"让{name}来查看进程列表吧~", 342 | f"收到!{name}这就帮你看看都有什么进程在运行呢", 343 | f"明白了,{name}来帮你查看当前的进程情况" 344 | ], 345 | "taskinfo": [ 346 | f"{name}来看看系统现在的状态如何~", 347 | f"让{name}检查一下系统性能呢", 348 | f"好的,{name}这就帮你查看系统状态" 349 | ], 350 | "taskkill": [ 351 | f"{name}这就帮你结束这个进程~", 352 | f"交给{name}吧,马上帮你关掉它", 353 | f"明白了,{name}来帮你终止这个进程" 354 | ], 355 | "type": [ 356 | f"{name}来帮你输入文字啦~", 357 | f"让{name}来帮你输入吧", 358 | f"好的,{name}这就帮你输入文字" 359 | ], 360 | "move": [ 361 | f"{name}来帮你移动鼠标~", 362 | f"交给{name}吧,马上帮你移动到指定位置", 363 | f"明白了,{name}来帮你控制鼠标" 364 | ], 365 | "click": [ 366 | f"{name}来帮你点击~", 367 | f"让{name}来帮你点击吧", 368 | f"好的,{name}这就帮你点击" 369 | ], 370 | "shortcut": [ 371 | f"{name}来帮你按快捷键啦~", 372 | f"让{name}来帮你按组合键吧", 373 | f"好的,{name}这就帮你按快捷键" 374 | ], 375 | "open": [ 376 | f"{name}来帮你打开文件~", 377 | f"让{name}来帮你打开吧", 378 | f"好的,{name}这就帮你打开文件" 379 | ], 380 | "cmd": [ 381 | f"{name}来帮你执行命令~", 382 | f"让{name}来帮你运行命令吧", 383 | f"好的,{name}这就帮你执行命令" 384 | ] 385 | } 386 | 387 | if cmd_type in responses: 388 | return random.choice(responses[cmd_type]) 389 | return f"好的,让{name}来帮你完成这个任务~" 390 | 391 | print(f"\n{Fore.BLUE}{self.persona.get('name','AI')}: {Style.RESET_ALL}{get_persona_response(cmd)}") 392 | 393 | if cmd == "tasklist": 394 | processes = self.system_monitor.get_process_list() 395 | result = "\n进程列表(按CPU使用率排序):\n" 396 | result += "PID".ljust(8) + "名称".ljust(20) + "CPU".ljust(10) + "内存".ljust(10) 397 | result += "状态".ljust(10) + "用户".ljust(15) + "创建时间".ljust(20) + "\n" 398 | result += "-" * 90 + "\n" 399 | 400 | for proc in processes: 401 | result += f"{str(proc['pid']).ljust(8)}" 402 | result += f"{proc['name'][:18].ljust(20)}" 403 | result += f"{f'{proc['cpu']:.1f}%'.ljust(10)}" 404 | result += f"{f'{proc['memory']:.1f}%'.ljust(10)}" 405 | result += f"{proc['status'][:8].ljust(10)}" 406 | result += f"{str(proc['user'])[:13].ljust(15)}" 407 | result += f"{proc['created']}\n" 408 | print(result) 409 | elif cmd == "taskinfo": 410 | info = self.system_monitor.get_performance_info() 411 | result = "\n系统性能信息:\n" 412 | result += f"CPU使用率: {info['cpu']['usage']}% | 频率: {info['cpu']['freq']}MHz\n" 413 | result += f"内存: {info['memory']['used']}/{info['memory']['total']} ({info['memory']['percent']}%)\n" 414 | result += f"磁盘: {info['disk']['used']}/{info['disk']['total']} ({info['disk']['percent']}%)" 415 | print(result) 416 | elif cmd == "taskkill" and args: 417 | target = int(args[0]) if args[0].isdigit() else args[0] 418 | result = self.system_monitor.kill_process(target) 419 | print(result) 420 | print(f"\n{Fore.BLUE}{self.persona.get('name','AI')}: {Style.RESET_ALL}进程已经被终止了,还需要我帮你做什么吗?") 421 | elif cmd == "type" and args: 422 | text = " ".join(args) 423 | for char in text: 424 | time.sleep(0.1) # 模拟打字间隔 425 | if char == " ": 426 | self.system_monitor.simulate_key_press("space") 427 | else: 428 | self.system_monitor.simulate_key_press(char) 429 | print("模拟输入完成") 430 | print(f"\n{Fore.BLUE}{self.persona.get('name','AI')}: {Style.RESET_ALL}文字已输入完成,还有什么需要我帮忙的吗?") 431 | elif cmd == "move" and len(args) == 2: 432 | try: 433 | x, y = map(int, args) 434 | result = self.system_monitor.simulate_mouse_move(x, y) # 有个傻比给变量名写错了 435 | print(result) 436 | print(f"\n{Fore.BLUE}{self.persona.get('name','AI')}: {Style.RESET_ALL}鼠标已移动到指定位置,需要我做些什么?") 437 | except ValueError: 438 | print("用法: /move x y (x和y必须是整数)") 439 | elif cmd == "click": 440 | button = args[0] if args else 'left' 441 | clicks = int(args[1]) if len(args) > 1 else 1 442 | self.system_monitor.simulate_click(button, clicks) 443 | print(f"模拟点击: {button} {clicks}次") 444 | print(f"\n{Fore.BLUE}{self.persona.get('name','AI')}: {Style.RESET_ALL}已完成点击操作,还需要其他帮助吗?") 445 | elif cmd == "shortcut" and args: 446 | self.system_monitor.simulate_shortcut(*args) 447 | print(f"模拟快捷键: {'+'.join(args)}") 448 | print(f"\n{Fore.BLUE}{self.persona.get('name','AI')}: {Style.RESET_ALL}快捷键已模拟完成,还有什么需要我做的?") 449 | elif cmd == "open" and args: 450 | self.system_monitor.open_file(args[0]) 451 | print(f"尝试打开文件: {args[0]}") 452 | print(f"\n{Fore.BLUE}{self.persona.get('name','AI')}: {Style.RESET_ALL}文件已打开,需要进一步的帮助吗?") 453 | elif cmd == "cmd" and args: 454 | result = self.system_monitor.execute_cmd(" ".join(args)) 455 | print(f"命令执行结果:\n{result}") 456 | print(f"\n{Fore.BLUE}{self.persona.get('name','AI')}: {Style.RESET_ALL}命令已执行完毕,还需要执行其他命令吗?") 457 | elif cmd == "camera": 458 | if not args: 459 | print("用法: /camera capture [文件名] 或 /camera preview [秒数]") 460 | elif args[0] == "capture": 461 | save_path = args[1] if len(args) > 1 else "capture.jpg" 462 | result = self.system_monitor.camera_capture(save_path) 463 | print(result) 464 | elif args[0] == "preview": 465 | duration = int(args[1]) if len(args) > 1 else 5 466 | result = self.system_monitor.camera_preview(duration) 467 | print(result) 468 | elif cmd == "help": 469 | print("可用命令:") 470 | print("/switch 后端 - 切换API后端") 471 | print("/model 模型 - 切换模型") 472 | print("/persona [名称 特征 背景] - 设置人设") 473 | print("/add 领域 知识 - 添加知识") 474 | print("/clear - 清空对话历史") 475 | print("/save - 保存配置") 476 | print("/filter add/remove 关键词 - 添加或移除敏感词") 477 | print("/reset - 重置知识库") 478 | print("/learn - 学习知识库文件夹中的所有文本") 479 | print("/forget - 遗忘所有已学习的知识") 480 | print("/system - 显示系统信息") 481 | print("/exit - 退出") 482 | print("/camera capture [文件名] - 拍摄照片") 483 | print("/camera preview [秒数] - 打开摄像头预览") 484 | else: 485 | print(f"\n{Fore.BLUE}{self.persona.get('name','AI')}: {Style.RESET_ALL}抱歉,我不太理解这个命令。输入 /help 可以查看所有支持的命令哦!") 486 | 487 | def main_loop(self): 488 | print(Fore.CYAN + "\n欢迎使用Neuro-bot! 输入/help查看命令" + Style.RESET_ALL) 489 | while True: 490 | try: 491 | user_input = input(Fore.GREEN + "\n你: " + Style.RESET_ALL).strip() 492 | 493 | if not user_input: 494 | continue 495 | 496 | if user_input.startswith("/"): 497 | cmd, *args = user_input[1:].split(" ") 498 | self.handle_command(cmd, args) 499 | else: 500 | start_time = time.time() 501 | print("\n" + Fore.YELLOW + "思考中..." + Style.RESET_ALL, end="", flush=True) 502 | timer_stop = threading.Event() 503 | 504 | def update_timer(): 505 | while not timer_stop.is_set(): 506 | print("\r" + Fore.YELLOW + f"思考中... {time.time() - start_time:.1f}s" + 507 | Style.RESET_ALL, end="", flush=True) 508 | time.sleep(1) 509 | 510 | timer_thread = threading.Thread(target=update_timer) 511 | timer_thread.daemon = True 512 | timer_thread.start() 513 | 514 | response = self.chat(user_input) 515 | timer_stop.set() 516 | timer_thread.join() 517 | 518 | elapsed_time = time.time() - start_time 519 | print("\r" + " " * 30 + "\r", end="") 520 | print(f"{Fore.BLUE}{self.persona.get('name','AI')}: {Style.RESET_ALL}{response}") 521 | print(Fore.YELLOW + f" 思考时间: {elapsed_time:.2f}秒" + Style.RESET_ALL) 522 | 523 | except (KeyboardInterrupt, EOFError): 524 | print(Fore.YELLOW + "\n使用/exit退出程序" + Style.RESET_ALL) 525 | except Exception as e: 526 | print(Fore.RED + f"错误: {e}" + Style.RESET_ALL) 527 | 528 | def main(): 529 | bot = ChatBot() 530 | print(Fore.CYAN + "\n欢迎使用Neuro-bot! 输入/help查看命令" + Style.RESET_ALL) 531 | while True: 532 | try: 533 | user_input = input(Fore.GREEN + "\n你: " + Style.RESET_ALL).strip() 534 | if not user_input: 535 | continue 536 | if user_input.startswith("/"): 537 | cmd, *args = user_input[1:].split(" ", 1) 538 | if cmd == "exit": 539 | bot.save_config() 540 | print("再见!") 541 | break 542 | elif cmd == "switch" and args: 543 | bot.switch_backend(args[0]) 544 | elif cmd == "model" and args: 545 | bot.switch_model(args[0]) 546 | elif cmd == "persona": 547 | if args: 548 | parts = args[0].split(" ", 2) 549 | bot.update_persona( 550 | parts[0] if len(parts) > 0 else None, 551 | parts[1] if len(parts) > 1 else None, 552 | parts[2] if len(parts) > 2 else None 553 | ) 554 | else: 555 | print("当前人设:", json.dumps(bot.persona, indent=2, ensure_ascii=False)) 556 | elif cmd == "add" and args: 557 | if " " in args[0]: 558 | domain, knowledge = args[0].split(" ", 1) 559 | bot.add_knowledge(domain, knowledge) 560 | else: 561 | print("用法: /add 领域 知识内容") 562 | elif cmd == "clear": 563 | bot.clear_history() 564 | elif cmd == "save": 565 | bot.save_config() 566 | elif cmd == "filter": 567 | if not args: 568 | print("用法: /filter add/remove 关键词") 569 | else: 570 | action, word = args[0].split(" ", 1) 571 | if action == "add": 572 | bot.content_filter.add_word(word) 573 | print(f"已添加敏感词: {word}") 574 | elif action == "remove": 575 | bot.content_filter.remove_word(word) 576 | print(f"已移除敏感词: {word}") 577 | elif cmd == "reset": 578 | bot.reset_knowledge() 579 | elif cmd == "system": 580 | sys_info = bot.get_system_info() 581 | print("\n系统信息:") 582 | for key, value in sys_info.items(): 583 | print(f"{key}: {value}") 584 | elif cmd == "help": 585 | print("可用命令:") 586 | print("/switch 后端 - 切换API后端") 587 | print("/model 模型 - 切换模型") 588 | print("/persona [名称 特征 背景] - 设置人设") 589 | print("/add 领域 知识 - 添加知识") 590 | print("/clear - 清空对话历史") 591 | print("/save - 保存配置") 592 | print("/filter add/remove 关键词 - 添加或移除敏感词") 593 | print("/reset - 重置知识库") 594 | print("/learn - 学习知识库文件夹中的所有文本") 595 | print("/forget - 遗忘所有已学习的知识") 596 | print("/system - 显示系统信息") 597 | print("/exit - 退出") 598 | print("/camera capture [文件名] - 拍摄照片") 599 | print("/camera preview [秒数] - 打开摄像头预览") 600 | elif cmd == "learn": 601 | count = bot.knowledge_system.learn_all() 602 | bot.knowledge_base = bot.knowledge_system.get_all_knowledge() 603 | print(f"已学习 {count} 条新知识") 604 | elif cmd == "forget": 605 | count = bot.knowledge_system.forget_all() 606 | bot.knowledge_base = bot.knowledge_system.get_all_knowledge() 607 | print(f"已遗忘 {count} 条知识") 608 | else: 609 | print("未知命令,输入/help查看帮助") 610 | else: 611 | start_time = time.time() 612 | print("\n" + Fore.YELLOW + "思考中..." + Style.RESET_ALL, end="", flush=True) 613 | timer_stop = threading.Event() 614 | 615 | def update_timer(): 616 | while not timer_stop.is_set(): 617 | print("\r" + Fore.YELLOW + f"思考中... {time.time() - start_time:.1f}s" + 618 | Style.RESET_ALL, end="", flush=True) 619 | time.sleep(1) 620 | 621 | timer_thread = threading.Thread(target=update_timer) 622 | timer_thread.daemon = True 623 | timer_thread.start() 624 | 625 | response = bot.chat(user_input) 626 | timer_stop.set() 627 | timer_thread.join() 628 | 629 | elapsed_time = time.time() - start_time 630 | print("\r" + " " * 30 + "\r", end="") 631 | print(f"{Fore.BLUE}{bot.persona.get('name','AI')}: {Style.RESET_ALL}{response}") 632 | print(Fore.YELLOW + f"思考时间: {elapsed_time:.2f}秒" + Style.RESET_ALL) 633 | 634 | except (KeyboardInterrupt, EOFError): 635 | print(Fore.YELLOW + "\n使用/exit退出程序" + Style.RESET_ALL) 636 | except Exception as e: 637 | print(Fore.RED + f"错误: {e}" + Style.RESET_ALL) 638 | 639 | if __name__ == "__main__": 640 | main() 641 | 642 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------