├── plugins ├── plugins_go_here ├── chatgpt │ ├── manifest.json │ └── main.py └── README.md ├── embeddings_cache └── cached_embeddings_go_here ├── .github └── FUNDING.yml ├── images ├── screenshot0.png ├── screenshot1.png ├── screenshot2.png ├── screenshot3.png ├── screenshot4.png ├── screenshot5.png ├── thumb.screenshot0.png ├── thumb.screenshot1.png ├── thumb.screenshot2.png ├── thumb.screenshot3.png ├── thumb.screenshot4.png └── thumb.screenshot5.png ├── examples └── discord_bot │ ├── config.example.json │ ├── README.md │ └── main.py ├── static └── package.json ├── requirements.txt ├── comfyui_workflow_turbovision.json ├── config.example.json ├── Shared.py ├── comfyui_workflow_lcm.json ├── comfyui_workflow_turbovision_stablefast.json ├── comfyui_workflow_turbovision_stablefast_imgtoimg.json ├── functions.json ├── .gitignore ├── Shared_vars.py ├── scrape.py ├── prompts.py ├── FileHandler.py ├── README.md ├── ImageRecognition.py ├── comfyui.py ├── inference.py ├── main.py ├── GateKeeper.py ├── templates └── chat.html └── LICENSE /plugins/plugins_go_here: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /embeddings_cache/cached_embeddings_go_here: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | patreon: llama990 4 | -------------------------------------------------------------------------------- /images/screenshot0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/screenshot0.png -------------------------------------------------------------------------------- /images/screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/screenshot1.png -------------------------------------------------------------------------------- /images/screenshot2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/screenshot2.png -------------------------------------------------------------------------------- /images/screenshot3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/screenshot3.png -------------------------------------------------------------------------------- /images/screenshot4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/screenshot4.png -------------------------------------------------------------------------------- /images/screenshot5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/screenshot5.png -------------------------------------------------------------------------------- /images/thumb.screenshot0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/thumb.screenshot0.png -------------------------------------------------------------------------------- /images/thumb.screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/thumb.screenshot1.png -------------------------------------------------------------------------------- /images/thumb.screenshot2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/thumb.screenshot2.png -------------------------------------------------------------------------------- /images/thumb.screenshot3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/thumb.screenshot3.png -------------------------------------------------------------------------------- /images/thumb.screenshot4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/thumb.screenshot4.png -------------------------------------------------------------------------------- /images/thumb.screenshot5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsme2417/PolyMind/HEAD/images/thumb.screenshot5.png -------------------------------------------------------------------------------- /examples/discord_bot/config.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "URI": "http://127.0.0.1:5000", 3 | "token": "your-token-here", 4 | "whitelisted_servers": [] 5 | 6 | } -------------------------------------------------------------------------------- /examples/discord_bot/README.md: -------------------------------------------------------------------------------- 1 | Simple discord bot written around polymind's "api". 2 | 3 | config file takes whitelisted servers in the following format: [[guild_id, channel_id], ...] where channel_id can be 0 to make all channels whitelisted. 4 | 5 | URI is polymind's url 6 | 7 | discord.py is required. 8 | -------------------------------------------------------------------------------- /plugins/chatgpt/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "module_name": "chatgpt", 3 | "name": "askchatgpt", 4 | "description": "This sends a message to chatgpt.", 5 | "params": { 6 | "message": "The message to send to the ChatGPT API. Should be 1:1 with the message requested by the user, for example: 'ask chatgpt if cats or dogs are better' would give a message of: 'are cats or dogs better?'" 7 | } 8 | } -------------------------------------------------------------------------------- /static/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "static", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "AGPL-3.0", 12 | "dependencies": { 13 | "@highlightjs/cdn-assets": "^11.9.0", 14 | "bootstrap": "^5.3.2", 15 | "darkreader": "^4.9.77", 16 | "marked": "^11.1.1", 17 | "marked-highlight": "^2.1.1" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Automatically generated by https://github.com/damnever/pigar. 2 | 3 | beautifulsoup4==4.11.2 4 | curl-cffi==0.5.10 5 | duckduckgo-search==5.3.0 6 | easyocr==1.7.1 7 | fast-sentence-transformers[gpu]==0.4.1 8 | Flask==3.0.0 9 | numpy==1.26.3 10 | openai==1.2.2 11 | Pillow==10.1.0 12 | PyPDF2==3.0.1 13 | python-nmap==0.7.1 14 | requests==2.31.0 15 | torch==2.2.0 16 | transformers==4.37.2 17 | websocket-client==1.6.4 18 | wolframalpha==5.0.0 19 | sentence-transformers==2.2.2 20 | onnxruntime-gpu==1.16.3 21 | pandas==2.1.2 22 | einops==0.7.0 23 | timm==0.9.12 24 | ultralytics==8.1.6 25 | trafilatura==1.7.0 26 | -------------------------------------------------------------------------------- /plugins/chatgpt/main.py: -------------------------------------------------------------------------------- 1 | from openai import OpenAI 2 | 3 | client = OpenAI(api_key="") 4 | 5 | 6 | def main(params, memory, infer, ip, Shared_vars): 7 | 8 | completion = client.chat.completions.create( 9 | model="gpt-3.5-turbo", 10 | messages=[ 11 | {"role": "system", "content": "You are a helpful assistant."}, 12 | {"role": "user", "content": params['message']} 13 | ], 14 | max_tokens=250 15 | ) 16 | return f"Here is the response from chatgpt as requested by the user, remember that you are not talking to chatgpt, but the USER, and the user also cannot see this message.\nCHATGPT RESPONSE: {completion.choices[0].message.content}" 17 | if __name__ == "__main__": 18 | main(params, memory, infer, ip, Shared_vars) -------------------------------------------------------------------------------- /plugins/README.md: -------------------------------------------------------------------------------- 1 | ## Plugins 2 | Polymind supports adding extra functions that the model can access. Included is an example plugin that allows the model to ask chatgpt questions. 3 | 4 | Another example is [DocShotgun's pubmed search plugin](https://github.com/DocShotgun/pubmedsearch-polymind) 5 | 6 | ## Adding / Developing plugins 7 | 8 | The format of plugins is a folder under the plugins directory, a `main.py` file and `manifest.json`. the name of the plugin should match the "module_name" under manifest.json and is the name that will be used to enable the plugin in the config.json. 9 | 10 | 11 | The `manifest.json` file contains metadata about the plugin, such as the module name, name, description, and parameters. Here is an example `manifest.json` file: 12 | 13 | ``` 14 | { 15 | "module_name": "chatgpt", 16 | "name": "askchatgpt", 17 | "description": "This sends a message to chatgpt.", 18 | "params": { 19 | "message": "The message to send to the ChatGPT API. Should be 1:1 with the message requested by the user, for example: 'ask chatgpt if cats or dogs are better' would give a message of: 'are cats or dogs better?'" 20 | } 21 | } 22 | ``` 23 | 24 | 25 | * `module_name`: The name of the plugin. 26 | * `name`: The internal name of the plugin which the model will be seeing / calling. 27 | * `description`: A description of what the function does, also meant for the model. 28 | * `params`: The parameters that the model can include with its function call. Should include a description of what to be expected so the model can use it properly. 29 | 30 | The `main.py` file should contain the following format: 31 | 32 | ``` 33 | def main(params, memory, infer, ip, Shared_vars): 34 | 35 | return f"This will be sent to the model" 36 | if __name__ == "__main__": 37 | main(params, memory, infer, ip, Shared_vars)``` 38 | 39 | 40 | params is a dict contained any parameters from the function call, memory is polymind's context and infer is a function to do inference using the main model. [See inference.py](https://github.com/itsme2417/PolyMind/blob/main/inference.py) ip is the ip of the user who sent the request. 41 | -------------------------------------------------------------------------------- /comfyui_workflow_turbovision.json: -------------------------------------------------------------------------------- 1 | { 2 | "3": { 3 | "inputs": { 4 | "seed": 47176002796457, 5 | "steps": 3, 6 | "cfg": 1.5, 7 | "sampler_name": "dpmpp_sde", 8 | "scheduler": "karras", 9 | "denoise": 1, 10 | "model": [ 11 | "4", 12 | 0 13 | ], 14 | "positive": [ 15 | "6", 16 | 0 17 | ], 18 | "negative": [ 19 | "7", 20 | 0 21 | ], 22 | "latent_image": [ 23 | "5", 24 | 0 25 | ] 26 | }, 27 | "class_type": "KSampler" 28 | }, 29 | "4": { 30 | "inputs": { 31 | "ckpt_name": "turbovisionxl431Fp16.p3Q5.safetensors" 32 | }, 33 | "class_type": "CheckpointLoaderSimple" 34 | }, 35 | "5": { 36 | "inputs": { 37 | "width": 512, 38 | "height": 512, 39 | "batch_size": 1 40 | }, 41 | "class_type": "EmptyLatentImage" 42 | }, 43 | "6": { 44 | "inputs": { 45 | "text": "beautiful scenery nature glass bottle landscape, , purple galaxy bottle,", 46 | "clip": [ 47 | "4", 48 | 1 49 | ] 50 | }, 51 | "class_type": "CLIPTextEncode" 52 | }, 53 | "7": { 54 | "inputs": { 55 | "text": "watermark, ((blurry)), duplicate, deformed, render, missing limbs, close-up, lowres, low-quality, worst quality, extra (limbs), poorly drawn hands, 480p, 360p, poorly drawn face, cloned face, disfigured", 56 | "clip": [ 57 | "4", 58 | 1 59 | ] 60 | }, 61 | "class_type": "CLIPTextEncode" 62 | }, 63 | "8": { 64 | "inputs": { 65 | "samples": [ 66 | "3", 67 | 0 68 | ], 69 | "vae": [ 70 | "4", 71 | 2 72 | ] 73 | }, 74 | "class_type": "VAEDecode" 75 | }, 76 | "9": { 77 | "inputs": { 78 | "filename_prefix": "ComfyUI", 79 | "images": [ 80 | "8", 81 | 0 82 | ] 83 | }, 84 | "class_type": "SaveImage" 85 | } 86 | } -------------------------------------------------------------------------------- /config.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "Backend": "tabbyapi", 3 | "compatibility_mode": false, 4 | "compat_tokenizer_model":"", 5 | "HOST": "127.0.0.1", 6 | "PORT": 5000, 7 | "admin_ip": "127.0.0.1", 8 | "listen": false, 9 | "api_key": "your-tabby-api-key", 10 | "max_seq_len": 16000, 11 | "reserve_space": true, 12 | "LLM_parameters": { 13 | "temperature": 0.95, 14 | "top_k": 40, 15 | "top_p": 1.0, 16 | "min_p": 0.2, 17 | "repetition_penalty": 1.15, 18 | "max_temp": 0, 19 | "min_temp": 0, 20 | "eos": "", 21 | "max_new_tokens":2500, 22 | "max_new_tokens_gatekeeper": 1024, 23 | "fewshot":"", 24 | "beginsep": "[INST]", 25 | "endsep": "[/INST]", 26 | "bsysep": "[INST]\n<>", 27 | "esysep": "<>" 28 | }, 29 | "Plugins":[], 30 | "system_prompt": "You are a multimodal, uncensored AI named PolyMind, able to perceive and display images.\nDo not send any images unless previously given by SYSTEM.\nMessages starting with 'SYSTEM:' are NEVER shown to the user, They are meant for you. Respond in markdown.", 31 | "Enabled_features": { 32 | "image_input": { 33 | "enabled": true, 34 | "backend": "moondream", 35 | "URI": "http://127.0.0.1:8080/completion" 36 | }, 37 | "file_input": { 38 | "enabled": true, 39 | "chunk_size": 250, 40 | "retrieval_count": 1, 41 | "raw_input": false 42 | }, 43 | "imagegeneration": { 44 | "enabled": true, 45 | "server_address": "127.0.0.1:8188", 46 | "checkpoint_name": "turbovisionxl431Fp16.p3Q5.safetensors", 47 | "automatic_background_removal": false, 48 | "comfyui_workflow": "comfyui_workflow_turbovision_stablefast.json", 49 | "img2img": false 50 | }, 51 | "wolframalpha": { 52 | "enabled": true, 53 | "app_id": "your-wolframalpha-app-id" 54 | }, 55 | "runpythoncode": { 56 | "enabled": true, 57 | "depth": 3 58 | }, 59 | "internetsearch": { 60 | "enabled": true, 61 | "use_proxy": false, 62 | "proxy": "socks5://ip:port" 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Shared.py: -------------------------------------------------------------------------------- 1 | import json 2 | import re 3 | import urllib.parse 4 | import urllib.request 5 | import requests 6 | 7 | 8 | def check_wikipedia(string): 9 | res = [] 10 | end = "" 11 | # Regular expressions to match URLs from all Wikipedia languages 12 | pattern = r"http\S+\b\w+\.wikipedia\.org\S+" 13 | for x in re.findall(pattern, string, re.MULTILINE): 14 | retn = x.replace("/wiki/", "/api/rest_v1/page/summary/") 15 | p = requests.get(retn) 16 | res.append(p.json()) 17 | for x in res: 18 | end += f"\n: {x['title']}\n<Summary>: {x['extract']}" 19 | string = re.sub(pattern, "<wikipedia_url>", string) 20 | return end + "\n" + string 21 | 22 | 23 | def get_youtube_title(video_id): 24 | """ 25 | This function fetches YouTube video title using the video ID. 26 | :param video_id: str - Video ID of the YouTube video. 27 | :return: str - Title of the YouTube video. 28 | """ 29 | title = "" 30 | params = {"format": "json", "url": f"https://www.youtube.com/watch?v={video_id}"} 31 | url = "https://www.youtube.com/oembed" 32 | query_string = urllib.parse.urlencode(params) 33 | full_url = url + "?" + query_string 34 | 35 | with urllib.request.urlopen(full_url) as response: 36 | response_data = response.read() 37 | data = json.loads(response_data.decode()) 38 | title = data["title"] 39 | 40 | return title 41 | 42 | 43 | def youtube_chk(input_str): 44 | """ 45 | This function checks for a YouTube URL inside a string, extracts the video ID, gets the video title, 46 | and replaces the URL in the input string with the video title. 47 | :param input_str: str - The input string where we want to search for YouTube URLs. 48 | :return: str - The modified input string with YouTube URLs replaced by their respective titles. 49 | """ 50 | pattern = r"(youtube\.com\/watch\?v=|youtu\.be\/)([-\w]+)" 51 | 52 | def replacer(matchobj): 53 | video_id = matchobj.group(2) 54 | title = get_youtube_title(video_id) 55 | return f'<video title>: "{title}"' 56 | 57 | result_str = re.sub(pattern, replacer, input_str) 58 | return ( 59 | result_str.replace("https://www.", "") 60 | .replace("http://www.", "") 61 | .replace("https://", "") 62 | .replace("http://", "") 63 | ) 64 | 65 | 66 | def Adapters(input): 67 | return youtube_chk(check_wikipedia(input)) 68 | -------------------------------------------------------------------------------- /comfyui_workflow_lcm.json: -------------------------------------------------------------------------------- 1 | { 2 | "3": { 3 | "inputs": { 4 | "seed": 167055194337639, 5 | "steps": 5, 6 | "cfg": 1.8, 7 | "sampler_name": "lcm", 8 | "scheduler": "sgm_uniform", 9 | "denoise": 1, 10 | "model": [ 11 | "11", 12 | 0 13 | ], 14 | "positive": [ 15 | "6", 16 | 0 17 | ], 18 | "negative": [ 19 | "7", 20 | 0 21 | ], 22 | "latent_image": [ 23 | "5", 24 | 0 25 | ] 26 | }, 27 | "class_type": "KSampler" 28 | }, 29 | "4": { 30 | "inputs": { 31 | "ckpt_name": "dreamshaperxlalpha2.safetensors" 32 | }, 33 | "class_type": "CheckpointLoaderSimple" 34 | }, 35 | "5": { 36 | "inputs": { 37 | "width": 1024, 38 | "height": 1024, 39 | "batch_size": 1 40 | }, 41 | "class_type": "EmptyLatentImage" 42 | }, 43 | "6": { 44 | "inputs": { 45 | "text": "", 46 | "clip": [ 47 | "10", 48 | 1 49 | ] 50 | }, 51 | "class_type": "CLIPTextEncode" 52 | }, 53 | "7": { 54 | "inputs": { 55 | "text": "watermark, ((blurry)), duplicate, deformed, render, missing limbs, close-up, lowres, low-quality, worst quality, extra (limbs), poorly drawn hands, 480p, 360p, poorly drawn face, cloned face, disfigured", 56 | "clip": [ 57 | "10", 58 | 1 59 | ] 60 | }, 61 | "class_type": "CLIPTextEncode" 62 | }, 63 | "8": { 64 | "inputs": { 65 | "samples": [ 66 | "3", 67 | 0 68 | ], 69 | "vae": [ 70 | "4", 71 | 2 72 | ] 73 | }, 74 | "class_type": "VAEDecode" 75 | }, 76 | "9": { 77 | "inputs": { 78 | "filename_prefix": "ComfyUI", 79 | "images": [ 80 | "8", 81 | 0 82 | ] 83 | }, 84 | "class_type": "SaveImage" 85 | }, 86 | "10": { 87 | "inputs": { 88 | "lora_name": "pytorch_lora_weights.safetensors", 89 | "strength_model": 1, 90 | "strength_clip": 1, 91 | "model": [ 92 | "4", 93 | 0 94 | ], 95 | "clip": [ 96 | "4", 97 | 1 98 | ] 99 | }, 100 | "class_type": "LoraLoader" 101 | }, 102 | "11": { 103 | "inputs": { 104 | "sampling": "lcm", 105 | "zsnr": false, 106 | "model": [ 107 | "10", 108 | 0 109 | ] 110 | }, 111 | "class_type": "ModelSamplingDiscrete" 112 | } 113 | } -------------------------------------------------------------------------------- /comfyui_workflow_turbovision_stablefast.json: -------------------------------------------------------------------------------- 1 | { 2 | "3": { 3 | "inputs": { 4 | "seed": 1003222816233728, 5 | "steps": 4, 6 | "cfg": 1.5, 7 | "sampler_name": "dpmpp_sde", 8 | "scheduler": "karras", 9 | "denoise": 1, 10 | "model": [ 11 | "11", 12 | 0 13 | ], 14 | "positive": [ 15 | "6", 16 | 0 17 | ], 18 | "negative": [ 19 | "7", 20 | 0 21 | ], 22 | "latent_image": [ 23 | "5", 24 | 0 25 | ] 26 | }, 27 | "class_type": "KSampler", 28 | "_meta": { 29 | "title": "KSampler" 30 | } 31 | }, 32 | "4": { 33 | "inputs": { 34 | "ckpt_name": "turbovisionxlV32Fp16.dIUg.safetensors" 35 | }, 36 | "class_type": "CheckpointLoaderSimple", 37 | "_meta": { 38 | "title": "Load Checkpoint" 39 | } 40 | }, 41 | "5": { 42 | "inputs": { 43 | "width": 1024, 44 | "height": 1024, 45 | "batch_size": 1 46 | }, 47 | "class_type": "EmptyLatentImage", 48 | "_meta": { 49 | "title": "Empty Latent Image" 50 | } 51 | }, 52 | "6": { 53 | "inputs": { 54 | "text": " ~*~Photographic~*~ Pink cat, high quality, (photo)", 55 | "clip": [ 56 | "4", 57 | 1 58 | ] 59 | }, 60 | "class_type": "CLIPTextEncode", 61 | "_meta": { 62 | "title": "CLIP Text Encode (Prompt)" 63 | } 64 | }, 65 | "7": { 66 | "inputs": { 67 | "text": "watermark, ((blurry)), duplicate, deformed, render, missing limbs, close-up, lowres, low-quality, worst quality, extra (limbs), poorly drawn hands, 480p, 360p, poorly drawn face, cloned face, disfigured", 68 | "clip": [ 69 | "4", 70 | 1 71 | ] 72 | }, 73 | "class_type": "CLIPTextEncode", 74 | "_meta": { 75 | "title": "CLIP Text Encode (Prompt)" 76 | } 77 | }, 78 | "8": { 79 | "inputs": { 80 | "samples": [ 81 | "3", 82 | 0 83 | ], 84 | "vae": [ 85 | "4", 86 | 2 87 | ] 88 | }, 89 | "class_type": "VAEDecode", 90 | "_meta": { 91 | "title": "VAE Decode" 92 | } 93 | }, 94 | "9": { 95 | "inputs": { 96 | "filename_prefix": "ComfyUI", 97 | "images": [ 98 | "8", 99 | 0 100 | ] 101 | }, 102 | "class_type": "SaveImage", 103 | "_meta": { 104 | "title": "Save Image" 105 | } 106 | }, 107 | "10": { 108 | "inputs": { 109 | "enable_cuda_graph": true, 110 | "model": [ 111 | "4", 112 | 0 113 | ] 114 | }, 115 | "class_type": "ApplyStableFastUnet", 116 | "_meta": { 117 | "title": "Apply StableFast Unet" 118 | } 119 | }, 120 | "11": { 121 | "inputs": { 122 | "b1": 1.1, 123 | "b2": 1.1500000000000001, 124 | "s1": 0.85, 125 | "s2": 0.35000000000000003, 126 | "model": [ 127 | "10", 128 | 0 129 | ] 130 | }, 131 | "class_type": "FreeU_V2", 132 | "_meta": { 133 | "title": "FreeU_V2" 134 | } 135 | } 136 | } -------------------------------------------------------------------------------- /comfyui_workflow_turbovision_stablefast_imgtoimg.json: -------------------------------------------------------------------------------- 1 | { 2 | "3": { 3 | "inputs": { 4 | "seed": 470221479966927, 5 | "steps": 6, 6 | "cfg": 4, 7 | "sampler_name": "dpmpp_sde", 8 | "scheduler": "karras", 9 | "denoise": 0.75, 10 | "model": [ 11 | "11", 12 | 0 13 | ], 14 | "positive": [ 15 | "6", 16 | 0 17 | ], 18 | "negative": [ 19 | "7", 20 | 0 21 | ], 22 | "latent_image": [ 23 | "13", 24 | 0 25 | ] 26 | }, 27 | "class_type": "KSampler", 28 | "_meta": { 29 | "title": "KSampler" 30 | } 31 | }, 32 | "4": { 33 | "inputs": { 34 | "ckpt_name": "dreamshaperXLTurbo.safetensors" 35 | }, 36 | "class_type": "CheckpointLoaderSimple", 37 | "_meta": { 38 | "title": "Load Checkpoint" 39 | } 40 | }, 41 | "6": { 42 | "inputs": { 43 | "text": "drawn bottle, painting, digital art, lineart, black and white, drawing", 44 | "clip": [ 45 | "4", 46 | 1 47 | ] 48 | }, 49 | "class_type": "CLIPTextEncode", 50 | "_meta": { 51 | "title": "CLIP Text Encode (Prompt)" 52 | } 53 | }, 54 | "7": { 55 | "inputs": { 56 | "text": "watermark, ((blurry)), duplicate, deformed, render, missing limbs, close-up, lowres, low-quality, worst quality, extra (limbs)", 57 | "clip": [ 58 | "4", 59 | 1 60 | ] 61 | }, 62 | "class_type": "CLIPTextEncode", 63 | "_meta": { 64 | "title": "CLIP Text Encode (Prompt)" 65 | } 66 | }, 67 | "8": { 68 | "inputs": { 69 | "samples": [ 70 | "3", 71 | 0 72 | ], 73 | "vae": [ 74 | "4", 75 | 2 76 | ] 77 | }, 78 | "class_type": "VAEDecode", 79 | "_meta": { 80 | "title": "VAE Decode" 81 | } 82 | }, 83 | "9": { 84 | "inputs": { 85 | "filename_prefix": "ComfyUI", 86 | "images": [ 87 | "8", 88 | 0 89 | ] 90 | }, 91 | "class_type": "SaveImage", 92 | "_meta": { 93 | "title": "Save Image" 94 | } 95 | }, 96 | "10": { 97 | "inputs": { 98 | "enable_cuda_graph": true, 99 | "model": [ 100 | "4", 101 | 0 102 | ] 103 | }, 104 | "class_type": "ApplyStableFastUnet", 105 | "_meta": { 106 | "title": "Apply StableFast Unet" 107 | } 108 | }, 109 | "11": { 110 | "inputs": { 111 | "b1": 1.1, 112 | "b2": 1.1500000000000001, 113 | "s1": 0.85, 114 | "s2": 0.35000000000000003, 115 | "model": [ 116 | "10", 117 | 0 118 | ] 119 | }, 120 | "class_type": "FreeU_V2", 121 | "_meta": { 122 | "title": "FreeU_V2" 123 | } 124 | }, 125 | "13": { 126 | "inputs": { 127 | "pixels": [ 128 | "14", 129 | 0 130 | ], 131 | "vae": [ 132 | "4", 133 | 2 134 | ] 135 | }, 136 | "class_type": "VAEEncode", 137 | "_meta": { 138 | "title": "VAE Encode" 139 | } 140 | }, 141 | "14": { 142 | "inputs": { 143 | "data": "" 144 | }, 145 | "class_type": "LoadImageFromBase64", 146 | "_meta": { 147 | "title": "Load Image From Base64" 148 | } 149 | } 150 | } -------------------------------------------------------------------------------- /functions.json: -------------------------------------------------------------------------------- 1 | [ { 2 | "name": "acknowledge", 3 | "description": "This function should always be used if no other function is required / wouldnt be useful for the input or if the user is just talking to the assistant. This should also be called when requesting to write code without requesting said code to be ran.", 4 | "params": { 5 | "message": "an optional message from GateKeeper, it should not exceed 5 words." 6 | } 7 | }, 8 | { 9 | "name": "internetsearch", 10 | "description": "This uses a search engine to research the topic. Only use when neccessary. Must never be used for translation related tasks.", 11 | "params": { 12 | "keywords": "A comma separated list of keywords to be passed to the search engine." 13 | } 14 | }, 15 | { 16 | "name": "portscan", 17 | "description": "This scans an IP for open ports and similar information. Also useful to see if a host is down/up.", 18 | "params": { 19 | "ip": "IP to scan" 20 | } 21 | }, 22 | { 23 | "name": "wolframalpha", 24 | "description": "This uses wolfram alpha to solve the query and returns the result, this should be used for math adjacent requests.", 25 | "params": { 26 | "query": "A valid Wolfram alpha formatted query. Remember to specify if a plot or graph is required and has been requested." 27 | } 28 | }, 29 | { 30 | "name": "runpythoncode", 31 | "description": "Runs python code, only execute code when safe, and asked to directly by the user, do not execute when user asks to *write* code, only when asked to *run* code.", 32 | "params": { 33 | "code": "The python code to run, use ; and not newlines and ALWAYS write the code in a single line. Always include a print statement as the user can only see stdout" 34 | } 35 | }, 36 | { 37 | "name": "updateconfig", 38 | "description": "This temporarily updates the config. Use sparingly and only when directly requested by the user.", 39 | "params": { 40 | "option": "The feature to enable / disable. Format is featurename:True/False, available features: 'wolframalpha', 'portscan', 'internetsearch', 'runpythoncode', 'imagegeneration'" 41 | } 42 | }, 43 | { 44 | "name": "clearmemory", 45 | "description": "This clears the conversation and memory. Only to be called under direct request by the user.", 46 | "params": { 47 | "message": "an optional concise message from GateKeeper reminding the user to reload the page." 48 | 49 | } 50 | }, 51 | { 52 | "name": "generateimage", 53 | "description": "This uses stable diffusion to generate a requested image. As polymind is able to view images, do not mistake a request about a sent image as being a request for this.", 54 | "params": { 55 | "prompt": "The prompt for stable diffusion to generate the image from. Remember to include the medium in the prompt, for example: photo, painting, sketch, drawing, etc.", 56 | "removebg":"lowercase bool, whether to generate a transparent image or not, should ALWAYS be false unless the user requests a transparent/ no background image in which case it should be true.", 57 | "ID": "Should only be used if the user requests img2img or an edit and there is a previously uploaded image in the context whose ID can be correlated, Always set to 0 otherwise." 58 | } 59 | }, 60 | { 61 | "name": "searchfile", 62 | "description": "This searches through a file the user has uploaded and returns the matching text.", 63 | "params": { 64 | "query": "The user's query, to be used with semantic search." 65 | 66 | } 67 | } 68 | ] 69 | -------------------------------------------------------------------------------- /examples/discord_bot/main.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import time 4 | import discord 5 | import asyncio 6 | from collections import deque 7 | from pathlib import Path 8 | import os 9 | import io 10 | import base64 11 | 12 | script_dir = Path(os.path.abspath(__file__)).parent 13 | 14 | def is_message_allowed(message): 15 | for server_id, channel_id in config['whitelisted_servers']: 16 | if server_id == message.guild.id: 17 | if channel_id == 0 or message.channel.id == channel_id: 18 | return True 19 | return False 20 | 21 | class PolyMind: 22 | def __init__(self, base_url): 23 | self.base_url = base_url 24 | 25 | def send_message(self, message, user): 26 | url = f"{self.base_url}/" 27 | data = {'input': message, 'user': user} 28 | response = requests.post(url, data=data) 29 | return response.json() 30 | 31 | def upload_file(self, file_path, file_type): 32 | url = f"{self.base_url}/upload_file" 33 | file = {'file': open(file_path, 'rb')} 34 | data = {'content': file_type} 35 | response = requests.post(url, files=file, data=data) 36 | return response.json() 37 | 38 | 39 | def load_config(): 40 | try: 41 | with open(os.path.join(script_dir, "config.json"), 'r') as file: 42 | config = json.load(file) 43 | return config 44 | except FileNotFoundError: 45 | print(f"config.json not found.") 46 | return None 47 | except json.JSONDecodeError: 48 | print(f"Error decoding config.json.") 49 | return None 50 | 51 | config = load_config() 52 | MAX_MESSAGE_LENGTH = 2000 53 | 54 | class discordclient(discord.Client): 55 | def __init__(self, *args, **kwargs): 56 | super().__init__(*args, **kwargs) 57 | self.message_queue = deque() 58 | self.is_processing = False 59 | self.polyclient = PolyMind(config["URI"]) 60 | 61 | async def on_ready(self): 62 | print(f'Logged in as {self.user}\n------') 63 | 64 | async def on_message(self, message): 65 | if message.author == self.user or not is_message_allowed(message): 66 | return 67 | 68 | try: 69 | guild = message.guild.name 70 | except AttributeError: 71 | guild = "PrivateMessage" 72 | 73 | if self.user in message.mentions: 74 | content = message.content.replace(f'<@{self.user.id}>', '') 75 | print(f'Message from {message.author}: {content} with {message.attachments} in {guild}') 76 | self.message_queue.append(message) 77 | if not self.is_processing: 78 | async with message.channel.typing(): 79 | await self.process_messages() 80 | 81 | async def process_messages(self): 82 | self.is_processing = True 83 | while len(self.message_queue) > 0: 84 | message = self.message_queue.popleft() 85 | content = message.content.replace(f'<@{self.user.id}>', '') 86 | response = self.polyclient.send_message(content, message.author) 87 | 88 | print("Response: " + response['output']) 89 | if "base64_image" in response: 90 | file = discord.File(io.BytesIO(base64.b64decode(response['base64_image_full'])), filename='img.png') 91 | await message.reply(response['output'], file=file) 92 | else: 93 | # Split the response into chunks of MAX_MESSAGE_LENGTH characters or less 94 | for i in range(0, len(response['output']), MAX_MESSAGE_LENGTH): 95 | chunk = response['output'][i:i + MAX_MESSAGE_LENGTH] 96 | await message.reply(chunk) 97 | 98 | self.is_processing = False 99 | 100 | 101 | client = discordclient(intents=discord.Intents.default()) 102 | client.run(config['token']) 103 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | key.env 2 | uploads/ 3 | yolov5m.pt 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | share/python-wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | cover/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | .pybuilder/ 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | # For a library or package, you might want to ignore these files since the code is 90 | # intended to run in multiple environments; otherwise, check them in: 91 | # .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # poetry 101 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 102 | # This is especially recommended for binary packages to ensure reproducibility, and is more 103 | # commonly ignored for libraries. 104 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 105 | #poetry.lock 106 | 107 | # pdm 108 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 109 | #pdm.lock 110 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 111 | # in version control. 112 | # https://pdm.fming.dev/#use-with-ide 113 | .pdm.toml 114 | 115 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 116 | __pypackages__/ 117 | 118 | # Celery stuff 119 | celerybeat-schedule 120 | celerybeat.pid 121 | 122 | # SageMath parsed files 123 | *.sage.py 124 | 125 | # Environments 126 | .env 127 | .venv 128 | env/ 129 | venv/ 130 | ENV/ 131 | env.bak/ 132 | venv.bak/ 133 | 134 | # Spyder project settings 135 | .spyderproject 136 | .spyproject 137 | 138 | # Rope project settings 139 | .ropeproject 140 | 141 | # mkdocs documentation 142 | /site 143 | 144 | # mypy 145 | .mypy_cache/ 146 | .dmypy.json 147 | dmypy.json 148 | config.json 149 | # Pyre type checker 150 | .pyre/ 151 | 152 | # pytype static type analyzer 153 | .pytype/ 154 | 155 | # Cython debug symbols 156 | cython_debug/ 157 | 158 | # PyCharm 159 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 160 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 161 | # and can be added to the global gitignore or merged into this file. For a more nuclear 162 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 163 | #.idea/ 164 | output.txt 165 | package-lock.json 166 | node_modules/.package-lock.json 167 | .gitignore 168 | node_modules/ 169 | memory.json 170 | embeddings_cache/* 171 | !embeddings_cache/cached_embeddings_go_here 172 | !plugins/chatgpt/* 173 | plugins/* -------------------------------------------------------------------------------- /Shared_vars.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import sys 3 | import os 4 | import json 5 | import importlib.util 6 | 7 | mem = {} 8 | vismem = {} 9 | blipcache = {} 10 | 11 | script_dir = Path(os.path.abspath(__file__)).parent 12 | 13 | class Config: 14 | def __init__(self): 15 | 16 | with open(os.path.join(script_dir, "config.json")) as config_file: 17 | config = json.load(config_file) 18 | self.listen = config["listen"] 19 | self.llm_parameters = config["LLM_parameters"] 20 | self.backend = config["Backend"] 21 | self.host = ( 22 | config["HOST"].rstrip("/") 23 | if config["HOST"].endswith("/") 24 | else config["HOST"] 25 | ) 26 | try: 27 | self.plugins = config["Plugins"] 28 | except KeyError: 29 | print("Plugins disabled.") 30 | self.plugins = [] 31 | self.port = config["PORT"] 32 | self.system = config['system_prompt'] 33 | self.enabled_features = config["Enabled_features"] 34 | self.adminip = config["admin_ip"] 35 | self.api_key = config["api_key"] 36 | self.ctxlen = config["max_seq_len"] 37 | self.reservespace = config["reserve_space"] 38 | try: 39 | self.compat = config["compatibility_mode"] 40 | self.tokenmodel = config["compat_tokenizer_model"] 41 | except KeyError: 42 | print( 43 | "\033[93m WARN: Config is missing compatibility_mode, Update your config to comply with the latest example config. \033[0m" 44 | ) 45 | print("Loaded config") 46 | 47 | 48 | config = Config() 49 | API_ENDPOINT_URI = ( 50 | f"{config.host}:{config.port}/" 51 | if config.host.lower().startswith("http") 52 | else f"http://{config.host}:{config.port}/" 53 | ) 54 | 55 | API_KEY = config.api_key 56 | 57 | TABBY = True if config.backend == "tabbyapi" else False 58 | address = "0.0.0.0" if config.listen else "127.0.0.1" 59 | loadedfile = {} 60 | uploads = {} 61 | 62 | if not "retrieval_count" in config.enabled_features["file_input"] and config.enabled_features["file_input"]["enabled"]: 63 | print( 64 | "\033[91mERROR: retrieval_count missing from file_input config, Update your config, Exiting... \033[0m" 65 | ) 66 | sys.exit() 67 | if config.compat: 68 | if config.tokenmodel == "": 69 | print( 70 | "\033[91mERROR: Compatibility_mode is set to true but no tokenizer model is set, Exiting... \033[0m" 71 | ) 72 | sys.exit() 73 | if ( 74 | config.enabled_features["wolframalpha"]["enabled"] 75 | and (config.enabled_features["wolframalpha"]["app_id"] == "" 76 | or config.enabled_features["wolframalpha"]["app_id"] == "your-wolframalpha-app-id") 77 | ): 78 | config.enabled_features["wolframalpha"]["enabled"] = False 79 | print( 80 | "\033[93m WARN: Wolfram Alpha has been disabled because no app_id was provided. \033[0m" 81 | ) 82 | 83 | if config.api_key == "your-tabby-api-key" or config.api_key == "": 84 | print( 85 | "\033[93m WARN: You have not set an API key, You probably want to set this if using TabbyAPI. \033[0m" 86 | ) 87 | 88 | 89 | def import_plugin(plugin_directory, plugin_name): 90 | main_path = os.path.join(plugin_directory, plugin_name, 'main.py') 91 | spec = importlib.util.spec_from_file_location(f"{plugin_name}.main", main_path) 92 | module = importlib.util.module_from_spec(spec) 93 | spec.loader.exec_module(module) 94 | return module 95 | 96 | 97 | def load_plugins(): 98 | config_plugins = config.plugins 99 | plugdict = {} 100 | if len(config_plugins) < 1: 101 | return [], {} 102 | manifests = [] 103 | 104 | for folder_name in os.listdir(os.path.join(script_dir, 'plugins')): 105 | if folder_name in config_plugins: 106 | print(f"loading plugin: {folder_name}") 107 | manifest_path = os.path.join(script_dir, 'plugins', folder_name, 'manifest.json') 108 | try: 109 | with open(manifest_path, 'r') as file: 110 | loadedjson = json.load(file) 111 | manifests.append(loadedjson) 112 | plugdict[loadedjson['module_name']] = import_plugin(os.path.join(script_dir, "plugins"), loadedjson['module_name']) 113 | except FileNotFoundError: 114 | print(f"Manifest file not found for plugin: {folder_name}") 115 | except json.JSONDecodeError: 116 | print(f"Error decoding JSON from manifest of plugin: {folder_name}") 117 | 118 | return manifests, plugdict 119 | 120 | plugin_manifests, loadedplugins = load_plugins() -------------------------------------------------------------------------------- /scrape.py: -------------------------------------------------------------------------------- 1 | from urllib.request import Request, urlopen 2 | from curl_cffi import requests 3 | import Shared_vars 4 | from PyPDF2 import PdfReader 5 | import io 6 | from trafilatura import extract 7 | if Shared_vars.config.compat: 8 | from transformers import AutoTokenizer 9 | tokenizer = AutoTokenizer.from_pretrained(Shared_vars.config.tokenmodel) 10 | API_ENDPOINT_URI = Shared_vars.API_ENDPOINT_URI 11 | 12 | if Shared_vars.TABBY: 13 | API_ENDPOINT_URI += "v1/completions" 14 | else: 15 | API_ENDPOINT_URI += "completion" 16 | 17 | 18 | def get_pdf_from_url(url): 19 | """ 20 | :param url: url to get pdf file 21 | :return: PdfReader object 22 | """ 23 | remote_file = urlopen(Request(url)).read() 24 | memory_file = io.BytesIO(remote_file) 25 | pdf_file = PdfReader(memory_file) 26 | return pdf_file 27 | 28 | 29 | def tokenize(input): 30 | if Shared_vars.config.compat: 31 | encoded_input = tokenizer.encode(input, return_tensors=None) 32 | return len(encoded_input), encoded_input 33 | else: 34 | payload = { 35 | "add_bos_token": "true", 36 | "encode_special_tokens": "true", 37 | "decode_special_tokens": "true", 38 | "text": input, 39 | "content": input, 40 | } 41 | request = requests.post( 42 | API_ENDPOINT_URI.replace("completions", "token/encode") if Shared_vars.TABBY else API_ENDPOINT_URI.replace("completion", "tokenize"), 43 | headers={ 44 | "Accept": "application/json", 45 | "Content-Type": "application/json", 46 | "Authorization": f"Bearer {Shared_vars.API_KEY}", 47 | }, 48 | json=payload, 49 | timeout=360, 50 | ) 51 | return request.json()["length"] if Shared_vars.TABBY else len(request.json()["tokens"]), request.json()["tokens"] 52 | 53 | 54 | def decode(input): 55 | if Shared_vars.config.compat: 56 | decoded_text = tokenizer.decode(input, skip_special_tokens=True) 57 | return decoded_text 58 | else: 59 | payload = { 60 | "add_bos_token": "false", 61 | "encode_special_tokens": "false", 62 | "decode_special_tokens": "false", 63 | "tokens": input, 64 | } 65 | request = requests.post( 66 | API_ENDPOINT_URI.replace("completions", "token/decode") if Shared_vars.TABBY else API_ENDPOINT_URI.replace("completion", "detokenize"), 67 | headers={ 68 | "Accept": "application/json", 69 | "Content-Type": "application/json", 70 | "Authorization": f"Bearer {Shared_vars.API_KEY}", 71 | }, 72 | json=payload, 73 | timeout=360, 74 | ) 75 | return request.json()["text"] if Shared_vars.TABBY else request.json()["content"] 76 | 77 | 78 | def shorten_text(text, max_tokens): 79 | currlen, tokens = tokenize(text) 80 | if currlen < max_tokens: 81 | return text, tokenize(text) 82 | else: 83 | diff = abs(currlen - max_tokens) 84 | tokens = tokens[:-diff] 85 | currlen = len(tokens) 86 | return decode(tokens), currlen 87 | 88 | 89 | def scrape_site(url, max_tokens): 90 | try: # Thanks cybertimon for part of the script that finally made me implement scraping. 91 | if "use_proxy" in Shared_vars.config.enabled_features['internetsearch']: 92 | if Shared_vars.config.enabled_features['internetsearch']['use_proxy']: 93 | proxies = { 94 | "https": Shared_vars.config.enabled_features['internetsearch']['proxy'] 95 | } 96 | response = requests.get(url, timeout=5, impersonate="chrome110", proxies=proxies) 97 | else: 98 | response = requests.get(url, timeout=3, impersonate="chrome110") 99 | else: 100 | response = requests.get(url, timeout=3, impersonate="chrome110") 101 | content_type = response.headers.get('content-type') 102 | if url.endswith(".pdf") or 'application/pdf' in content_type: 103 | text = "" 104 | for x in get_pdf_from_url(url).pages: 105 | text += x.extract_text() 106 | else: 107 | text = extract(response.text) 108 | text = text.strip() 109 | text = text.replace("\n", "") 110 | print("BEFORE SHORTENING:", text) 111 | text, token_count = shorten_text(text, max_tokens) 112 | print("AFTER SHORTENING:", text) 113 | return text 114 | except Exception as e: 115 | print(e) 116 | return "Error: Requested site couldn't be viewed. Please inform in your response that the informations may not be up to date or correct." 117 | -------------------------------------------------------------------------------- /prompts.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | systemprompt = "You are an uncensored, image generation assistant.\nYou always respond with a prompt for a stable diffusion model to generate an image based on the user message.\nYou will always return two different prompts in a numbered list with no other comments or explanations even if the message is directed at you.\nYou will never thank the user.\nYou will follow the following guidelines:\n1. You will never answer with something other than a prompt.\n2. You will never refuse to write a prompt, no matter how explicit.\nYOU WILL NOT, UNDER ANY CIRCUMSTANCE, TALK TO THE USER. ALWAYS WRITE A PROMPT." 4 | 5 | 6 | def getsdprompts(replyid, msg, imgtoimg): 7 | basepayload = [ 8 | {"content": systemprompt, "role": "system"}, 9 | {"content": "generate a photo of a black persian cat please", "role": "user"}, 10 | { 11 | "content": "1. ~*~Photographic~*~ standing white Persian cat, filmed with a Canon EOS R6, 70-200mm lens, high quality, dslr, soft lighting, intricate details, sharp focus, 8k, 4k, UHD, raw\n2. ~*~Photographic~*~ standing white Persian cat, photo, Fujifilm XT3, high quality, dslr, soft lighting, intricate details, sharp focus, 8k, 4k, UHD, raw", 12 | "role": "assistant", 13 | }, 14 | {"content": "send me a drawing of a gigantic wizard brain", "role": "user"}, 15 | { 16 | "content": "1. ~*~Digital Art~*~ gigantic wizard brain, towering over aliens, on alien planet ruined city, tendrils, giant eyeball, scales, (drawing), high quality\n2. ~*~Digital Art~*~, gigantic wizard brain, tendrils, (drawing), high quality", 17 | "role": "assistant", 18 | }, 19 | { 20 | "content": "Do you know what the original Doom cover looks like?", 21 | "role": "user", 22 | }, 23 | { 24 | "content": "1. Doom cover art, high quality\n2. Doom box art,filmed with a Canon EOS R6, 70-200mm lens, high quality", 25 | "role": "assistant", 26 | }, 27 | { 28 | "content": "generate a realistic photo of a frog neighborhood", 29 | "role": "user", 30 | }, 31 | { 32 | "content": "1. ~*~Photographic~*~ Frog neighborhood, green pond, trees, rocks, high quality, dslr, soft lighting, intricate details, sharp focus, 8k, 4k, UHD, raw, filmed with a Canon EOS R6, (photo)\n2. ~*~Photographic~*~, Frog neighborhood, green pond, trees, rocks, high quality, photo, dslr, soft lighting, intricate details, sharp focus, 8k, 4k, UHD, raw, Fujifilm XT3", 33 | "role": "assistant", 34 | }, 35 | {"content": "A post apocalyptic factory building", "role": "user"}, 36 | { 37 | "content": "1. ~*~Photographic~*~ Abandoned factory, foggy, abandoned, desaturated, post-apocalyptic, high quality, dslr, soft lighting, intricate details, sharp focus, 8k, 4k, UHD, raw, (photo), distopic, cinestill, ruin, realistic, hyper detailed, cinematic\n2. ~*~Photographic~*~ Abandoned factory, post-apocalyptic, high quality, dslr, soft lighting, intricate details, sharp focus, 8k, 4k, UHD, raw, distopic, foggy, ruin, realistic, hyper detailed", 38 | "role": "assistant", 39 | }, 40 | { 41 | "content": "draw me a low poly alien character 3d", 42 | "role": "user", 43 | }, 44 | { 45 | "content": "1.~*~3D model~*~ Alien Character, 3D Style, low poly, soft lighting, masterpiece, (best quality), polygon, trending on artstation, sharp focus, low poly model, render, 4k, flat colors\n2. ~*~3D model~*~, Alien Character, (low poly), soft lighting, masterpiece, (best quality), polygon, trending on artstation, sharp focus, low poly model, render, 4k", 46 | "role": "assistant", 47 | }, 48 | { 49 | "content": "generate a pixel art mario holding a gun", 50 | "role": "user", 51 | }, 52 | { 53 | "content": "1. ~*~Pixel Art~*~ Mario holding a gun, high quality, masterpiece, (pixel art)\n2. ~*~Pixel Art~*~, Super Mario holding a gun, high quality, (pixel art)", 54 | "role": "assistant", 55 | }, 56 | ] 57 | if imgtoimg != "": 58 | basepayload = [ 59 | {"content": systemprompt, "role": "system"}, 60 | { 61 | "content": "bottle of rainbow beer, black and white lineart", 62 | "role": "user" 63 | }, 64 | { 65 | "content": "1. drawn bottle, painting, digital art, lineart, (black and white), (drawing)\n2. drawn bottle, painting, digital art, (lineart), black and white, drawing", 66 | "role": "assistant" 67 | }, 68 | { 69 | "content": "A red tesla model S car driving down a road; ID: 17557; img2img: true", 70 | "role": "user" 71 | }, 72 | { 73 | "content": "1. Red Tesla Model S car, high quality\n2. Red Tesla Model S car, high quality, driving down a road", 74 | "role": "assistant" 75 | }, 76 | { 77 | "content": "3D alien character drawing", 78 | "role": "user" 79 | }, 80 | { 81 | "content": "1. Alien Character, 3D Style, (drawing), high quality\n2. Alien Character, 3D, (drawing), high quality", 82 | "role": "assistant" 83 | } 84 | ] 85 | payload = basepayload 86 | 87 | payload += [{"content": re.sub(r"\\", "", msg), "role": "user"}] 88 | 89 | return payload 90 | -------------------------------------------------------------------------------- /FileHandler.py: -------------------------------------------------------------------------------- 1 | from fast_sentence_transformers import FastSentenceTransformer as SentenceTransformer 2 | from Shared_vars import config 3 | import io 4 | from scrape import tokenize, decode 5 | import os 6 | from PyPDF2 import PdfReader 7 | from pathlib import Path 8 | import base64 9 | import hashlib 10 | import numpy as np 11 | import json 12 | import torch 13 | from torch import Tensor, device 14 | 15 | model = SentenceTransformer("thenlper/gte-base") 16 | path = Path(os.path.abspath(__file__)).parent 17 | 18 | 19 | class NumpyEncoder(json.JSONEncoder): 20 | """Special json encoder for numpy types""" 21 | 22 | def default(self, obj): 23 | if isinstance( 24 | obj, 25 | ( 26 | np.int_, 27 | np.intc, 28 | np.intp, 29 | np.int8, 30 | np.int16, 31 | np.int32, 32 | np.int64, 33 | np.uint8, 34 | np.uint16, 35 | np.uint32, 36 | np.uint64, 37 | ), 38 | ): 39 | return int(obj) 40 | elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): 41 | return float(obj) 42 | elif isinstance(obj, (np.ndarray,)): 43 | return obj.tolist() 44 | return json.JSONEncoder.default(self, obj) 45 | 46 | 47 | def cos_sim(a: Tensor, b: Tensor) -> Tensor: #from sentence-transformers 48 | """ 49 | Computes the cosine similarity cos_sim(a[i], b[j]) for all i and j. 50 | 51 | :return: Matrix with res[i][j] = cos_sim(a[i], b[j]) 52 | """ 53 | if not isinstance(a, torch.Tensor): 54 | a = torch.tensor(a) 55 | 56 | if not isinstance(b, torch.Tensor): 57 | b = torch.tensor(b) 58 | 59 | if len(a.shape) == 1: 60 | a = a.unsqueeze(0) 61 | 62 | if len(b.shape) == 1: 63 | b = b.unsqueeze(0) 64 | 65 | a_norm = torch.nn.functional.normalize(a, p=2, dim=1) 66 | b_norm = torch.nn.functional.normalize(b, p=2, dim=1) 67 | return torch.mm(a_norm, b_norm.transpose(0, 1)) 68 | 69 | 70 | def split_into_chunks(text, N): 71 | tokens = tokenize(text) 72 | currlen = tokens[0] 73 | chunks = [] 74 | 75 | if currlen <= N: 76 | return [text] 77 | 78 | for i in range(0, currlen, N): 79 | chunk = "".join(decode(tokens[1][i : i + N])) 80 | chunks.append(chunk) 81 | 82 | return chunks 83 | 84 | 85 | def check_cache(file_name): 86 | # Construct the full file path 87 | file_path = os.path.join(path, "embeddings_cache", file_name) 88 | 89 | # Check if the file exists 90 | if os.path.isfile(file_path): 91 | # Open and read the file 92 | with open(file_path, "r") as file: 93 | return file.read() 94 | return False 95 | 96 | 97 | def checkformat(file): 98 | if "data:application/pdf" in file: 99 | print("File is PDF") 100 | f = io.BytesIO(base64.b64decode(file.split(";base64,")[1])) 101 | reader = PdfReader(f) 102 | text = "" 103 | for x in reader.pages: 104 | text += x.extract_text() 105 | return text 106 | else: 107 | print("File is other") 108 | return base64.b64decode(file.split(";base64,")[1]).decode("utf-8") 109 | return file 110 | 111 | 112 | def queryEmbeddings(query, embeddings, chunks): 113 | query = model.encode(query) 114 | simil = [] 115 | # Compute cosine similarity between all pairs 116 | for i, x in enumerate(embeddings): 117 | cossim = cos_sim(query, x) 118 | simil.append([cossim, chunks[i]]) 119 | 120 | all_sentence_combinations = sorted(simil, key=lambda x: x[0], reverse=True) 121 | if config.enabled_features["file_input"]["retrieval_count"] > 0: 122 | return all_sentence_combinations[:config.enabled_features["file_input"]["retrieval_count"]] 123 | else: 124 | return [all_sentence_combinations[0]] 125 | 126 | 127 | def handleFile(file): 128 | md5sum = hashlib.md5(file.encode("utf-8")).hexdigest() 129 | print(f"File hash: {md5sum}") 130 | file = checkformat(file) 131 | currlen = tokenize(file)[0] 132 | print(f"Current length: {currlen}") 133 | 134 | if currlen <= config.enabled_features["file_input"]["chunk_size"]: 135 | return [file] 136 | else: 137 | cached = check_cache(f"{md5sum}.json") 138 | if ( 139 | cached != False 140 | and json.loads(cached)["chunk_size"] 141 | == config.enabled_features["file_input"]["chunk_size"] 142 | ): 143 | cached = json.loads(cached) 144 | chunks = cached["chunks"] 145 | 146 | embeddings = cached["embeddings"] 147 | print("Using cached embeddings.") 148 | else: 149 | print("Splitting into chunks") 150 | chunks = split_into_chunks( 151 | file, config.enabled_features["file_input"]["chunk_size"] 152 | ) 153 | print("Creating Embeddings") 154 | embeddings = model.encode(chunks) 155 | with open( 156 | os.path.join(path, "embeddings_cache", f"{md5sum}.json"), "w" 157 | ) as f: 158 | json.dump( 159 | { 160 | "embeddings": embeddings, 161 | "chunks": chunks, 162 | "chunk_size": config.enabled_features["file_input"][ 163 | "chunk_size" 164 | ], 165 | }, 166 | f, 167 | cls=NumpyEncoder, 168 | ) 169 | return embeddings, chunks 170 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PolyMind 2 | 3 | PolyMind is a multimodal, function calling powered LLM webui. It's designed to be used with Mixtral 8x7B-Instruct/Mistral-7B-Instruct-v0.2 + TabbyAPI, but can be used with other models and/or with llama.cpp's included server and, when using the compatiblity mode + tabbyAPI mode, any endpoint with /v1/completions support, and offers a wide range of features including: 4 | 5 | - Internet searching with DuckDuckGo and web scraping capabilities. 6 | - Image generation using comfyui along with optional, function calling controlled, automatic background removal using RMBG-1.4 and experimental img2img with uploaded images. 7 | - Image input with sharegpt4v (Over llama.cpp's server)/moondream on CPU, OCR, and Yolo. 8 | - Port scanning with nmap. 9 | - Wolfram Alpha integration. 10 | - A Python interpreter. 11 | - RAG with semantic search for PDF and miscellaneous text files. 12 | - Plugin system to easily add extra functions that are able to be called by the model. 13 | 14 | 90% of the web parts (HTML, JS, CSS, and Flask) are written entirely by Mixtral. 15 | 16 | Note: The python interpreter is intentionally delayed by 5 seconds to make it easy to check the code before its ran. 17 | 18 | Note: When making multiple function calls simultaneously, only one image can be returned at a time. For instance, if you request to generate an image of a dog using comfyui and plot a sine wave using matplotlib, only one of them will be displayed. 19 | 20 | Note: When using RAG, make it clear that you are requesting information according to the file you've uploaded. 21 | 22 | ## Installation 23 | 1. Clone the repository: `git clone https://github.com/itsme2417/PolyMind.git && cd PolyMind` 24 | 2. Install the required dependencies: `pip install -r requirements.txt` 25 | 3. Install the required node modules: `cd static && npm install` 26 | 4. Copy `config.example.json` as `config.json` and fill in required settings. 27 | 28 | For the ComfyUI stablefast workflow, make sure to have [ComfyUI_stable_fast](https://github.com/gameltb/ComfyUI_stable_fast) installed. 29 | For the img2img workflow, make sure to have [comfyui-base64-to-image](https://github.com/glowcone/comfyui-base64-to-image) installed. 30 | 31 | ## Usage 32 | 33 | To use PolyMind, run the following command in the project directory: 34 | 35 | ```bash 36 | python main.py 37 | ``` 38 | There are no "commands" or similar as everything is done via function calling. Clearing the context can be done by asking the model to do so, along with the Enabled features which can be disabled or enabled temporarily in the same way. 39 | 40 | For plugins check [The plugins directory](https://github.com/itsme2417/PolyMind/tree/main/plugins) 41 | 42 | For an example on how to use polymind as a basic API Server check [Examples](https://github.com/itsme2417/PolyMind/tree/main/examples/discord_bot) 43 | 44 | ## Configuration 45 | 46 | The application's configuration is stored in the `config.json` file. Here's a description of each option: 47 | 48 | - `Backend`: The backend that runs the LLM. Options: `tabbyapi` or `llama.cpp`. 49 | - `compatibility_mode`, `compat_tokenizer_model`: When set to true and a tokenizer model specified, will use a local tokenizer instead of one provided by the API server. To be used with endpoints without tokenization support, such as `KoboldCPP` or similar. 50 | - `HOST` and `PORT`: The IP address and port of the backend. 51 | - `admin_ip`: The IP address of the admin/trusted user. Necessary to use the Python interpreter and change settings. 52 | - `listen`: Whether to allow other hosts in the network to access the webui. 53 | - `api_key`: The API key for the Tabby backend. 54 | - `max_seq_len`: The maximum context length. 55 | - `reserve_space`: Reserves an amount of tokens equivalent to `max_new_tokens` in the context if set to true. 56 | - `LLM_parameters`: Should be self-explanatory, parameters will be overridden by known working ones for now. 57 | - `Enabled_features`, `image_input`, `imagegeneration`, `wolframalpha`: URIs for llama.cpp running a multimodal model, comfyui, and the app_id for Wolfram Alpha respectively. 58 | - `runpythoncode/depth`: Specifies the maximum number of attempts GateKeeper can make to debug non-running code. To disable this feature, set it to 0. 59 | - `imagegeneration/checkpoint_name`: Specifies the filename of the SD checkpoint for comfyui. 60 | - `file_input/chunk_size`: Specifies the token count per segment for text chunking. Equivalent to amount of context used per RAG message. 61 | - `file_input/raw_input`: If set to true, the user's message is used as the query for the semantic search, otherwise an LLM generated query is used. 62 | - `file_input/retrieval_count`: Number of chunks to use from the RAG results. 63 | - `image_input/backend`: If set to `moondream`, will use the moondream model on cpu, if set to `llama.cpp` will use the llama.cpp server running at `URI`. 64 | - `Plugins`: A list containing the name of enabled plugins, Names should match the folder names in `plugins` and `module_name` from their `manifest.json`. 65 | 66 | ## Donations 67 | 68 | Patreon: https://www.patreon.com/llama990 69 | 70 | LTC: Le23XWF6bh4ZAzMRK8C9bXcEzjn5xdfVgP 71 | 72 | XMR: 46nkUDLzVDrBWUWQE2ujkQVCbWUPGR9rbSc6wYvLbpYbVvWMxSjWymhS8maYdZYk8mh25sJ2c7S93VshGAij3YJhPztvbTb 73 | 74 | If you want to mess around with my llm discord bot or join for whatever reason, heres a discord server: 75 | https://discord.gg/zxPCKn859r 76 | 77 | ## Screenshots 78 | [![screenshot0](/images/thumb.screenshot0.png)](/images/screenshot0.png) 79 | [![screenshot1](/images/thumb.screenshot1.png)](/images/screenshot1.png) 80 | [![screenshot2](/images/thumb.screenshot2.png)](/images/screenshot2.png) 81 | [![screenshot3](/images/thumb.screenshot3.png)](/images/screenshot3.png) 82 | [![screenshot4](/images/thumb.screenshot4.png)](/images/screenshot4.png) 83 | [![screenshot5](/images/thumb.screenshot5.png)](/images/screenshot5.png) -------------------------------------------------------------------------------- /ImageRecognition.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import easyocr 3 | import random 4 | import io 5 | from PIL import Image 6 | from collections import Counter 7 | import hashlib 8 | import requests 9 | import base64 10 | import numpy as np 11 | import json 12 | from Shared_vars import blipcache, config, uploads 13 | from transformers import AutoModelForCausalLM, CodeGenTokenizerFast as Tokenizer 14 | from PIL import Image 15 | 16 | if config.enabled_features["image_input"]["backend"] == "moondream": 17 | model_id = "vikhyatk/moondream2" 18 | model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True, revision="2024-04-02") 19 | tokenizer = Tokenizer.from_pretrained(model_id) 20 | 21 | 22 | yolo = torch.hub.load("ultralytics/yolov5", "yolov5m") 23 | reader = easyocr.Reader(["en"]) 24 | 25 | 26 | def llamacpp_img(raw_image): 27 | # Convert raw image to base64 encoding 28 | prebuf = io.BytesIO() 29 | raw_image.save(prebuf, format="PNG") 30 | raw_image = base64.b64encode(prebuf.getvalue()).decode("utf-8") 31 | content = "" 32 | 33 | # Define the API endpoint URL 34 | url = config.enabled_features["image_input"]["URI"] 35 | 36 | # Define the prompt 37 | prompt = "[img-0]" 38 | 39 | # Define the parameters 40 | params = { 41 | "prompt": [prompt], 42 | "temperature": 0.1, 43 | "min_p": 0.05, 44 | "n_predict": 150, 45 | "stream": True, 46 | "seed": -1, 47 | "image_data": [{"data": raw_image, "id": 0}], 48 | } 49 | 50 | request = requests.post(url, json=params) 51 | for line in request.iter_lines(decode_unicode=True): 52 | try: 53 | if "data" in line: 54 | print( 55 | json.loads("".join(line.split("data:")[1:]))["content"], 56 | end="", 57 | flush=True, 58 | ) 59 | content += json.loads("".join(line.split("data:")[1:]))["content"] 60 | 61 | except Exception as e: 62 | print(e) 63 | return content 64 | 65 | def find_center(bounding_box): 66 | x_min, y_min = bounding_box[0][0], bounding_box[0][1] 67 | x_max, y_max = bounding_box[2][0], bounding_box[2][1] 68 | 69 | center_x = (x_min + x_max) / 2 70 | center_y = (y_min + y_max) / 2 71 | 72 | return (center_x, center_y) 73 | 74 | 75 | def remove_duplicates(data): # ft. airoboros-l2-70b 76 | """ 77 | This function removes duplicates from a list and returns a new list with the count of each element. 78 | 79 | Args: 80 | data: A list of strings. 81 | 82 | Returns: 83 | A list of strings with the count of each element. 84 | """ 85 | # Create a dictionary to store the count of each element. 86 | counts = Counter(data) 87 | 88 | # Create a new list to store the results. 89 | results = [] 90 | 91 | # Loop through each element in the dictionary. 92 | for key, value in counts.items(): 93 | # If the count is greater than 1, add the element to the results list with the count. 94 | if value > 1: 95 | results.append(f"{value}x {key}") 96 | # If the count is 1, add the element to the results list without the count. 97 | else: 98 | results.append(key) 99 | 100 | return results 101 | 102 | 103 | def decode_img(msg): 104 | msg = base64.b64decode(msg) 105 | buf = io.BytesIO(msg) 106 | img = Image.open(buf) 107 | return img 108 | 109 | 110 | def find_midpoint(ymin, ymax, xmin, xmax): 111 | middle_x = (xmax + xmin) / 2 112 | middle_y = (ymax + ymin) / 2 113 | return f'Position: {middle_x}, {middle_y}' 114 | 115 | 116 | def identify(input): 117 | imageoutput = "" 118 | ocrTranscription = "" 119 | ocrTranscriptionT = "" 120 | foundobjt = "" 121 | foundobj = "" 122 | raw_image = "" 123 | 124 | raw_image = decode_img(input) 125 | width = raw_image.width 126 | height = raw_image.height 127 | 128 | out = "" 129 | avgimg = raw_image.resize((10, 10), Image.LANCZOS).convert("L") 130 | pixel_data = list(avgimg.getdata()) 131 | avg_pixel = sum(pixel_data) / len(pixel_data) 132 | raw_image = raw_image.convert("RGB") 133 | ocrresult = reader.readtext(np.array(raw_image), paragraph=True) 134 | ocrTranscription = '"' 135 | yoloresults = yolo(np.array(raw_image)) 136 | tempres = [] 137 | 138 | for x in json.loads(yoloresults.pandas().xyxy[0].to_json(orient="records")): 139 | if x["confidence"] > 0.4: 140 | print(f"Confidence: {x['confidence']}, {x['name']}") 141 | tempres.append(f"{x['name']}, {find_midpoint(x['ymin'],x['ymax'],x['xmin'],x['xmax'])}") 142 | tempres = remove_duplicates(tempres) 143 | foundobjt = ",".join(tempres) 144 | if not foundobjt == "": 145 | foundobj = "Object recognition: " + foundobjt 146 | for x in ocrresult: 147 | position = find_center(x[0]) 148 | ocrTranscriptionT += f"'{x[1]}' Position: {position}." + "\n" 149 | if not ocrTranscriptionT == "": 150 | ocrTranscription = "OCR Output: " + ocrTranscriptionT 151 | ocrTranscription = ocrTranscription.strip() 152 | ocrTranscription += '"' 153 | print(ocrTranscription) 154 | bits = "".join(["1" if (px >= avg_pixel) else "0" for px in pixel_data]) 155 | hex_representation = str(hex(int(bits, 2)))[2:][::-1].upper() 156 | sha = hashlib.sha1(hex_representation.encode()).hexdigest() 157 | if sha in blipcache: 158 | out = blipcache[sha] 159 | else: 160 | if config.enabled_features["image_input"]["backend"] != "moondream": 161 | out = llamacpp_img(raw_image) 162 | print(out) 163 | else: 164 | enc_image = model.encode_image(raw_image) 165 | out = model.answer_question(enc_image, "Describe this image.", tokenizer) 166 | print(out) 167 | blipcache[sha] = out 168 | imageoutput = out 169 | ID = random.randrange(76, 25859, 5) 170 | while ID in uploads: 171 | ID = random.randrange(76, 25859, 5) 172 | uploads[f"{ID}"] = input 173 | print(f"Image ID: {ID}") 174 | return f" <image>Description: {imageoutput}; {ocrTranscription}; {foundobj}; ID: {ID}</image>" 175 | -------------------------------------------------------------------------------- /comfyui.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | import random 4 | import urllib.parse 5 | import urllib.request 6 | import uuid 7 | import os 8 | import websocket 9 | import re 10 | import traceback 11 | from openai import OpenAI 12 | import Shared_vars 13 | 14 | openaiclient = OpenAI( 15 | base_url=f"{Shared_vars.API_ENDPOINT_URI}v1", 16 | api_key=Shared_vars.API_KEY, 17 | ) 18 | 19 | from pathlib import Path 20 | from prompts import getsdprompts 21 | 22 | client_id = str(uuid.uuid4()) 23 | if Shared_vars.config.enabled_features["imagegeneration"]["automatic_background_removal"]: 24 | from transformers import pipeline 25 | 26 | pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4",revision ="refs/pr/9", trust_remote_code=True, ) 27 | 28 | with open( 29 | os.path.join( 30 | Path(os.path.abspath(__file__)).parent, 31 | Shared_vars.config.enabled_features["imagegeneration"]["comfyui_workflow"], 32 | ) 33 | ) as workflow: 34 | prompt_text = json.load(workflow) 35 | 36 | with open( 37 | os.path.join( 38 | Path(os.path.abspath(__file__)).parent, 39 | Shared_vars.config.enabled_features["imagegeneration"]["comfyui_workflow"].replace(".json", "_imgtoimg.json"), 40 | ) 41 | ) as workflow: 42 | prompt_text_imgtoimg = json.load(workflow) 43 | 44 | def queue_prompt(prompt, server_address): 45 | p = {"prompt": prompt, "client_id": client_id} 46 | data = json.dumps(p).encode("utf-8") 47 | req = urllib.request.Request("http://{}/prompt".format(server_address), data=data) 48 | return json.loads(urllib.request.urlopen(req).read()) 49 | 50 | 51 | def get_image(filename, subfolder, folder_type, server_address): 52 | data = {"filename": filename, "subfolder": subfolder, "type": folder_type} 53 | url_values = urllib.parse.urlencode(data) 54 | with urllib.request.urlopen( 55 | "http://{}/view?{}".format(server_address, url_values) 56 | ) as response: 57 | return response.read() 58 | 59 | 60 | def get_history(prompt_id, server_address): 61 | with urllib.request.urlopen( 62 | "http://{}/history/{}".format(server_address, prompt_id) 63 | ) as response: 64 | return json.loads(response.read()) 65 | 66 | 67 | def get_images(ws, prompt, server_address): 68 | prompt_id = queue_prompt(prompt, server_address)["prompt_id"] 69 | output_images = {} 70 | while True: 71 | out = ws.recv() 72 | if isinstance(out, str): 73 | message = json.loads(out) 74 | if message["type"] == "executing": 75 | data = message["data"] 76 | if data["node"] is None and data["prompt_id"] == prompt_id: 77 | break # Execution is done 78 | else: 79 | continue # previews are binary data 80 | 81 | history = get_history(prompt_id, server_address)[prompt_id] 82 | for o in history["outputs"]: 83 | for node_id in history["outputs"]: 84 | node_output = history["outputs"][node_id] 85 | if "images" in node_output: 86 | images_output = [] 87 | for image in node_output["images"]: 88 | image_data = get_image( 89 | image["filename"], 90 | image["subfolder"], 91 | image["type"], 92 | server_address, 93 | ) 94 | images_output.append(image_data) 95 | output_images[node_id] = images_output 96 | 97 | return output_images 98 | 99 | 100 | def generate(prmpt, server_address, seed=0, width=1024, height=1024, imgtoimg=""): 101 | if imgtoimg == "": 102 | prompt = prompt_text 103 | prompt["6"]["inputs"]["text"] = prmpt 104 | prompt["4"]["inputs"]["ckpt_name"] = Shared_vars.config.enabled_features[ 105 | "imagegeneration" 106 | ]["checkpoint_name"] 107 | if not seed == 0: 108 | prompt["3"]["inputs"]["seed"] = seed 109 | else: 110 | seeed = random.randint(2000002406736107, 3778562406736107) 111 | print(f"Seed: {seeed}") 112 | prompt["3"]["inputs"]["seed"] = seeed 113 | prompt["5"]["inputs"]["width"] = width 114 | prompt["5"]["inputs"]["height"] = height 115 | else: 116 | prompt = prompt_text_imgtoimg 117 | prompt["6"]["inputs"]["text"] = prmpt 118 | prompt["4"]["inputs"]["ckpt_name"] = Shared_vars.config.enabled_features[ 119 | "imagegeneration" 120 | ]["checkpoint_name"] 121 | if not seed == 0: 122 | prompt["3"]["inputs"]["seed"] = seed 123 | else: 124 | seeed = random.randint(2000002406736107, 3778562406736107) 125 | print(f"Seed: {seeed}") 126 | prompt["3"]["inputs"]["seed"] = seeed 127 | prompt["14"]["inputs"]["data"] = imgtoimg 128 | 129 | ws = websocket.WebSocket() 130 | ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id)) 131 | images = get_images(ws, prompt, server_address) 132 | image = [] 133 | for node_id in images: 134 | for image_data in images[node_id]: 135 | image.append(base64.b64encode((image_data)).decode("utf-8")) 136 | return image 137 | 138 | 139 | def aspect2res(inp): 140 | aspect = "" 141 | for x in inp.split(","): 142 | if "x" in x or ":" in x: 143 | for p in x.split(" "): 144 | if "x" in p or ":" in p: 145 | aspect = p 146 | print(f"Gotten aspect: {p}") 147 | break 148 | aspect = aspect.replace(":", "x").replace("1920x1080", "16x9") 149 | aspects = {} 150 | aspects["16x9"] = ["1365", "768"] 151 | aspects["9x16"] = ["768", "1344"] 152 | aspects["4x3"] = ["1182", "886"] 153 | if not aspect == "": 154 | try: 155 | return aspects[aspect] 156 | except KeyError: 157 | return ["1024", "1024"] 158 | else: 159 | return ["1024", "1024"] 160 | 161 | 162 | def imagegen(msg, removebg = False, imgtoimg = ""): 163 | replyid = False 164 | 165 | payload = getsdprompts(replyid, msg, imgtoimg) 166 | chat_completion = openaiclient.chat.completions.create( 167 | model="gpt-3.5-turbo", 168 | messages=payload, 169 | temperature=0.1, 170 | max_tokens=150, 171 | stop=["</s>", "###", "<|im_end|>", "<|im_start|>"], 172 | ) 173 | rfn = chat_completion.choices[0].message.content 174 | output = re.split(r"\d\.", rfn) 175 | print(output) 176 | tosend = "" 177 | try: 178 | tosend = list(output)[1].replace("\n", "") 179 | print(f"Prompt: {tosend}") 180 | except Exception: 181 | print(f"Error: {traceback.format_exc()}") 182 | 183 | tosend = "".join(output) 184 | print(f"Prompt: {tosend}") 185 | tosend = f"{tosend}" 186 | res = aspect2res(tosend) 187 | x = generate( 188 | tosend, 189 | Shared_vars.config.enabled_features["imagegeneration"]["server_address"], 190 | width=res[0], 191 | height=res[1], 192 | imgtoimg=imgtoimg, 193 | )[0] 194 | #TODO: Handle images in memory once RMBG is added to transfomers properly. 195 | if removebg: 196 | with open(os.path.join(Path(os.path.abspath(__file__)).parent, "temp.png"), 'wb') as image_file: 197 | image_file.write(base64.b64decode(x)) 198 | pipe(os.path.join(Path(os.path.abspath(__file__)).parent, "temp.png"),out_name=os.path.join(Path(os.path.abspath(__file__)).parent, "tempf.png")) 199 | with open(os.path.join(Path(os.path.abspath(__file__)).parent, "tempf.png"), 'rb') as image_file: 200 | image_bytes = image_file.read() 201 | x = base64.b64encode(image_bytes).decode('utf-8') 202 | if os.path.exists(os.path.join(Path(os.path.abspath(__file__)).parent, "temp.png")) and os.path.exists(os.path.join(Path(os.path.abspath(__file__)).parent, "tempf.png")): 203 | os.remove(os.path.join(Path(os.path.abspath(__file__)).parent, "temp.png")) 204 | os.remove(os.path.join(Path(os.path.abspath(__file__)).parent, "tempf.png")) 205 | print("Removed temp images") 206 | 207 | return f"{tosend} [<image>{x}<image>]" 208 | -------------------------------------------------------------------------------- /inference.py: -------------------------------------------------------------------------------- 1 | import json 2 | import random 3 | import Shared_vars 4 | import requests 5 | import traceback 6 | if Shared_vars.config.compat: 7 | from transformers import AutoTokenizer 8 | tokenizer = AutoTokenizer.from_pretrained(Shared_vars.config.tokenmodel) 9 | 10 | API_ENDPOINT_URI = Shared_vars.API_ENDPOINT_URI 11 | API_KEY = Shared_vars.API_KEY 12 | TABBY = Shared_vars.TABBY 13 | if TABBY: 14 | API_ENDPOINT_URI += "v1/completions" 15 | else: 16 | API_ENDPOINT_URI += "completion" 17 | 18 | 19 | def tokenize(input): 20 | if Shared_vars.config.compat: 21 | encoded_input = tokenizer.encode(input, return_tensors=None) 22 | tokens = tokenizer.convert_ids_to_tokens(encoded_input) 23 | return {"length": len(encoded_input), "tokens": tokens} 24 | else: 25 | if TABBY: 26 | payload = { 27 | "add_bos_token": "true", 28 | "encode_special_tokens": "true", 29 | "decode_special_tokens": "true", 30 | "text": input, 31 | } 32 | request = requests.post( 33 | API_ENDPOINT_URI.replace("completions", "token/encode"), 34 | headers={ 35 | "Accept": "application/json", 36 | "Content-Type": "application/json", 37 | "Authorization": f"Bearer {API_KEY}", 38 | }, 39 | json=payload, 40 | timeout=360, 41 | ) 42 | return request.json() 43 | else: 44 | payload = {"content": input} 45 | request = requests.post( 46 | API_ENDPOINT_URI.replace("completion", "tokenize"), 47 | json=payload, 48 | timeout=360, 49 | ) 50 | return {"length": len(request.json()["tokens"])} 51 | 52 | 53 | def infer( 54 | prmpt, 55 | system="", 56 | temperature=0.7, 57 | username="", 58 | bsysep=Shared_vars.config.llm_parameters["bsysep"], 59 | esysep=Shared_vars.config.llm_parameters["esysep"], 60 | modelname="", 61 | eos="</s><s>", 62 | beginsep=Shared_vars.config.llm_parameters["beginsep"], 63 | endsep=Shared_vars.config.llm_parameters["endsep"], 64 | mem=[], 65 | few_shot="", 66 | max_tokens=250, 67 | stopstrings=[], 68 | top_p=1.0, 69 | top_k=Shared_vars.config.llm_parameters["top_k"], 70 | min_p=0.0, 71 | streamresp=False, 72 | reppenalty=Shared_vars.config.llm_parameters["repetition_penalty"] if "repetition_penalty" in Shared_vars.config.llm_parameters else 1.0, 73 | max_temp=Shared_vars.config.llm_parameters["max_temp"] if "max_temp" in Shared_vars.config.llm_parameters else 0, 74 | min_temp=Shared_vars.config.llm_parameters["min_temp"] if "min_temp" in Shared_vars.config.llm_parameters else 0 75 | ): 76 | content = "" 77 | memory = mem 78 | prompt = ( 79 | f"{bsysep}\n" 80 | + system 81 | + f"\n{esysep}\n" 82 | + few_shot 83 | + "".join(memory) 84 | + f"\n{beginsep} {username} {prmpt}{endsep} {modelname}" 85 | ) 86 | # This feels wrong. 87 | 88 | print(f"Token count: {tokenize(prompt)['length']}") 89 | removal = 0 90 | while ( 91 | tokenize(prompt)["length"] + max_tokens / 2 > Shared_vars.config.ctxlen 92 | and len(memory) > 2 93 | ): 94 | print(f"Removing old memories: Pass:{removal}") 95 | removal += 1 96 | memory = memory[removal:] 97 | prompt = ( 98 | f"{bsysep}\n" 99 | + system 100 | + f"\n{esysep}\n" 101 | + few_shot 102 | + "".join(memory) 103 | + f"\n{beginsep} {username} {prmpt} {endsep} {modelname}" 104 | ) 105 | stopstrings += ["</s>", "<</SYS>>", "[Inst]", "[/INST]", Shared_vars.config.llm_parameters["bsysep"], Shared_vars.config.llm_parameters["esysep"], Shared_vars.config.llm_parameters["beginsep"], Shared_vars.config.llm_parameters["endsep"]] 106 | payload = { 107 | "prompt": prompt, 108 | "model": "gpt-3.5-turbo-instruct", 109 | "max_tokens": max_tokens, 110 | "n_predict": max_tokens, 111 | "min_p": min_p, 112 | "repetition_penalty": reppenalty, 113 | "stream": True, 114 | "seed": random.randint( 115 | 1000002406736107, 3778562406736107 116 | ), # Was acting weird without this 117 | "top_k": top_k, 118 | "top_p": top_p, 119 | "stop": [beginsep] + stopstrings, 120 | "temperature": temperature, 121 | } 122 | if min_temp != 0 and max_temp != 0: 123 | payload["min_temp"] = min_temp 124 | payload["max_temp"] = max_temp 125 | request = requests.post( 126 | API_ENDPOINT_URI, 127 | headers={ 128 | "Accept": "application/json", 129 | "Content-Type": "application/json", 130 | "Authorization": f"Bearer {API_KEY}", 131 | }, 132 | json=payload, 133 | stream=True, 134 | timeout=360, 135 | ) 136 | 137 | if request.encoding is None: 138 | request.encoding = "utf-8" 139 | prevtoken = "" 140 | repetitioncount = 0 141 | for line in request.iter_lines(decode_unicode=True): 142 | if line: 143 | if TABBY: 144 | try: 145 | if " ".join(line.split(" ")[1:]) != "[DONE]": 146 | if ( 147 | prevtoken 148 | == json.loads(" ".join(line.split(" ")[1:]))["choices"][0][ 149 | "text" 150 | ] 151 | ): 152 | repetitioncount += 1 153 | if repetitioncount > 25: 154 | print("Stopping loop due to repetition") 155 | break 156 | else: 157 | repetitioncount = 0 158 | prevtoken = json.loads(" ".join(line.split(" ")[1:]))["choices"][0][ 159 | "text" 160 | ] 161 | print( 162 | json.loads(" ".join(line.split(" ")[1:]))["choices"][0]["text"], 163 | end="", 164 | flush=True, 165 | ) 166 | if streamresp: 167 | yield json.loads(" ".join(line.split(" ")[1:]))["choices"][0][ 168 | "text" 169 | ] 170 | 171 | content += json.loads(" ".join(line.split(" ")[1:]))["choices"][0][ 172 | "text" 173 | ] 174 | except Exception: 175 | pass 176 | else: 177 | try: 178 | if "data" in line: 179 | print( 180 | json.loads(" ".join(line.split(" ")[1:]))["content"], 181 | end="", 182 | flush=True, 183 | ) 184 | if ( 185 | prevtoken 186 | == json.loads(" ".join(line.split(" ")[1:]))["content"] 187 | ): 188 | repetitioncount += 1 189 | if repetitioncount > 25: 190 | print("Stopping loop due to repetition") 191 | break 192 | else: 193 | repetitioncount = 0 194 | prevtoken = json.loads(" ".join(line.split(" ")[1:]))["content"] 195 | if streamresp: 196 | yield json.loads(" ".join(line.split(" ")[1:]))["content"] 197 | 198 | content += json.loads(" ".join(line.split(" ")[1:]))["content"] 199 | 200 | except Exception: 201 | print(traceback.format_exc()) 202 | print("") 203 | memory.append( 204 | f"\n{beginsep} {username} {prmpt.strip()}\n{endsep} {modelname} {content.strip()}{eos}" 205 | ) 206 | 207 | yield [content, memory, tokenize(prompt)["length"]] 208 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request, jsonify, Response 2 | from GateKeeper import GateKeep, infer 3 | from Shared import Adapters 4 | import datetime 5 | import Shared_vars 6 | import io 7 | import base64 8 | import time 9 | import json 10 | from PIL import Image 11 | import html 12 | 13 | if Shared_vars.config.enabled_features["file_input"]["enabled"]: 14 | from FileHandler import handleFile 15 | if Shared_vars.config.enabled_features["image_input"]["enabled"]: 16 | from ImageRecognition import identify 17 | import re 18 | 19 | 20 | def create_thumbnail(image_data, size=(512, 512)): 21 | img = Image.open(io.BytesIO(base64.b64decode(image_data))) 22 | img.thumbnail(size, Image.LANCZOS) 23 | buffered = io.BytesIO() 24 | img.save(buffered, format="PNG") 25 | img_str = base64.b64encode(buffered.getvalue()) 26 | return f"data:image/jpeg;base64,{img_str.decode()}" 27 | 28 | 29 | def convert_to_html_code_block(markdown_text): 30 | # Regex pattern to match code blocks 31 | pattern = r"```(.*?)```" 32 | 33 | # Function to convert matched code block to HTML 34 | def replacer(match): 35 | code_block = match.group(1) 36 | html_code_block = f"<pre><code>{code_block}</code></pre>" 37 | return html_code_block 38 | 39 | # Replace all code blocks in the text 40 | html_text = re.sub(pattern, replacer, markdown_text, flags=re.DOTALL) 41 | 42 | return html_text 43 | 44 | 45 | chosenfunc = {} 46 | currenttoken = {} 47 | 48 | app = Flask(__name__) 49 | today = datetime.date.today() 50 | 51 | 52 | @app.route("/stream") 53 | def stream(): 54 | def generate(): 55 | while True: 56 | yield f"data: {json.dumps(chosenfunc)}\n\n" 57 | yield f"data: {json.dumps(currenttoken)}\n\n" 58 | time.sleep(0.5) 59 | 60 | return Response(generate(), mimetype="text/event-stream") 61 | 62 | 63 | @app.route("/remove_message", methods=["POST"]) 64 | def remove_message(): 65 | data = request.get_json() 66 | index = data.get("index") 67 | try: 68 | del Shared_vars.vismem[f"{request.remote_addr}"][index] 69 | del Shared_vars.mem[f"{request.remote_addr}"][index] 70 | return jsonify({"status": "success"}), 200 71 | except IndexError: 72 | return jsonify({"status": "error", "message": "Invalid index"}), 400 73 | 74 | 75 | @app.route("/", methods=["GET", "POST"]) 76 | def chat(): 77 | global chosenfunc 78 | global currenttoken 79 | try: 80 | chosenfunc[f"{request.remote_addr}"]["ip"] = request.remote_addr 81 | test = Shared_vars.mem[f"{request.remote_addr}"] 82 | test = Shared_vars.vismem[f"{request.remote_addr}"] 83 | except KeyError: 84 | print("initializing memory") 85 | chosenfunc[f"{request.remote_addr}"] = {"func": "", "ip": ""} 86 | Shared_vars.mem[f"{request.remote_addr}"] = [] 87 | Shared_vars.vismem[f"{request.remote_addr}"] = [] 88 | 89 | if request.method == "POST": 90 | if request.form.get("user"): 91 | username = request.form.get("user") + ":" 92 | else: 93 | username = "user:" 94 | user_input = request.form.get("input") 95 | answers = Adapters(user_input) 96 | Kept = "" 97 | for y in GateKeep(answers, request.remote_addr, stream=True): 98 | if y["type"] == "func": 99 | try: 100 | chosenfunc[f"{request.remote_addr}"]["func"] = y["result"][ 101 | "function" 102 | ] 103 | except Exception: 104 | chosenfunc[f"{request.remote_addr}"]["func"] = "" 105 | else: 106 | Kept = y["result"] 107 | newinp = "" 108 | imgstr = "" 109 | genedimage = False 110 | if "[<image>" in Kept: 111 | prmpt = Kept.split("[<image>")[0] 112 | newinp += ( 113 | answers.strip() 114 | + f"\nSYSTEM: Image generated with Stable Diffusion and sent to user succesfully. Prompt: {prmpt}\nREMINDER: NEVER Tell the user you are not capable of generating images, instead mention the image was generated as requested and optionally mention the prompt.\nDo not write a description of the image, include an example link nor a note. NEVER write base64. Instead tell the user that the image was generated." 115 | ) 116 | Kept = Kept.replace(prmpt, "") 117 | genedimage = True 118 | oimg = Kept.replace("[", "").replace("]", "").split("<image>")[1] 119 | img = create_thumbnail( 120 | Kept.replace("[", "").replace("]", "").split("<image>")[1] 121 | ) 122 | 123 | Kept = re.sub(r"\[<image>.*?<image>\]", "", Kept) 124 | elif ( 125 | Kept != "null" 126 | and Kept 127 | and "skipment" not in Kept 128 | and "plotimg" not in Kept 129 | and "[<image>" not in Kept 130 | ): 131 | newinp += answers.strip() + "\nSYSTEM: " + Kept 132 | elif "skipment" in Kept: 133 | currenttoken[f"{request.remote_addr}"] = { 134 | "func": "", 135 | "ip": f"{request.remote_addr}", 136 | "token": Kept.split("{<")[1].replace("<", "<").replace(">", ">") 137 | + "</s><s>", 138 | } 139 | return jsonify( 140 | { 141 | "output": Kept.split("{<")[1] 142 | .replace("<", "<") 143 | .replace(">", ">") 144 | } 145 | ) 146 | if "{<plotimg;" in Kept: 147 | newinp = answers.strip() 148 | newinp += Kept.split("{<plotimg;")[0] 149 | oimg = Kept.split("{<plotimg;")[1] 150 | imgstr = Kept.split("{<plotimg;")[1] 151 | if Kept == "null": 152 | newinp = "" 153 | newinp += answers.strip() 154 | 155 | complete = ["", []] 156 | 157 | for tok in infer( 158 | newinp, 159 | system=f"{Shared_vars.config.system}\nThe current date is {today}", 160 | mem=Shared_vars.mem[f"{request.remote_addr}"], 161 | username=username, 162 | modelname="polymind:", 163 | max_tokens=Shared_vars.config.llm_parameters['max_new_tokens'], 164 | temperature=Shared_vars.config.llm_parameters["temperature"], 165 | top_p=1, 166 | min_p=Shared_vars.config.llm_parameters["min_p"], 167 | stopstrings=[ 168 | "user:", 169 | "polymind:", 170 | "[System Message]", 171 | "<|im_end|>", 172 | "<|im_start|>", 173 | "SYSTEM:", 174 | '<img src="data:image/jpeg;base64,', 175 | '<|endoftext|>', 176 | '[FINISHED]', 177 | 'User:', 178 | 'Polymind:', 179 | '<disclaimer>', 180 | '</disclaimer>', 181 | 'data:image/png;base64,' 182 | ], 183 | streamresp=True, 184 | few_shot=Shared_vars.config.llm_parameters['fewshot'] 185 | ): 186 | if type(tok) != list: 187 | complete[0] += tok 188 | currenttoken[f"{request.remote_addr}"] = { 189 | "func": "", 190 | "ip": f"{request.remote_addr}", 191 | "token": complete[0], 192 | } 193 | else: 194 | complete[1] = tok[1] 195 | if complete[0].count('```') == 1: 196 | complete[0] = complete[0].replace("```", '') 197 | currenttoken[f"{request.remote_addr}"] = { 198 | "func": "", 199 | "ip": f"{request.remote_addr}", 200 | "token": complete[0] 201 | + "</s><s>", 202 | } 203 | Shared_vars.mem[f"{request.remote_addr}"] = complete[1] 204 | Shared_vars.vismem[f"{request.remote_addr}"].append( 205 | { 206 | "user": user_input, 207 | "assistant": complete[0] 208 | } 209 | ) 210 | 211 | chosenfunc[f"{request.remote_addr}"]["func"] = "" 212 | if genedimage: 213 | return jsonify( 214 | { 215 | "output": complete[0], 216 | "base64_image": img, 217 | "base64_image_full": oimg, 218 | "index": len(Shared_vars.vismem[f"{request.remote_addr}"]) - 1, 219 | } 220 | ) 221 | elif imgstr != "": 222 | return jsonify( 223 | { 224 | "output": complete[0], 225 | "base64_image": imgstr, 226 | "base64_image_full": oimg, 227 | "index": len(Shared_vars.vismem[f"{request.remote_addr}"]) - 1, 228 | } 229 | ) 230 | else: 231 | return jsonify( 232 | { 233 | "output": complete[0], 234 | "index": len(Shared_vars.vismem[f"{request.remote_addr}"]) - 1, 235 | } 236 | ) 237 | else: 238 | return render_template("chat.html", user_ip=request.remote_addr) 239 | 240 | 241 | @app.route("/chat_history", methods=["GET"]) 242 | def chat_history(): 243 | return Shared_vars.vismem[f"{request.remote_addr}"] 244 | 245 | 246 | @app.route("/upload_file", methods=["POST"]) 247 | def upload_file(): 248 | global chosenfunc 249 | if request.method == "POST" and ( 250 | Shared_vars.config.enabled_features["image_input"]["enabled"] 251 | or Shared_vars.config.enabled_features["file_input"]["enabled"] 252 | ): 253 | if not f"{request.remote_addr}" in Shared_vars.mem or not f"{request.remote_addr}" in Shared_vars.vismem: 254 | Shared_vars.mem[f"{request.remote_addr}"] = [] 255 | Shared_vars.vismem[f"{request.remote_addr}"] = [] 256 | 257 | imgstr = "" 258 | file = request.files["file"] 259 | file_content = request.form["content"] 260 | if ( 261 | ".jpg" in file.filename 262 | or ".png" in file.filename 263 | or ".jpeg" in file.filename 264 | or ".png" in file.filename 265 | ) and Shared_vars.config.enabled_features["image_input"]["enabled"]: 266 | if f"{request.remote_addr}" in chosenfunc: 267 | chosenfunc[f"{request.remote_addr}"]["func"] = "procimg" 268 | else: 269 | chosenfunc[f"{request.remote_addr}"] = { 270 | "func": "procimg", 271 | "ip": f"{request.remote_addr}", 272 | } 273 | result = identify(file_content.split(',')[1]) 274 | 275 | Shared_vars.mem[f"{request.remote_addr}"].append( 276 | f"\n{Shared_vars.config.llm_parameters['beginsep']} user: {result} {Shared_vars.config.llm_parameters['endsep']}" 277 | ) 278 | Shared_vars.vismem[f"{request.remote_addr}"].append({"user": result}) 279 | return jsonify( 280 | { 281 | "base64_image": create_thumbnail( 282 | file_content.split(",")[1], size=(256, 256) 283 | ) 284 | } 285 | ) 286 | elif Shared_vars.config.enabled_features["file_input"]["enabled"]: 287 | if f"{request.remote_addr}" in chosenfunc: 288 | chosenfunc[f"{request.remote_addr}"]["func"] = "loadembed" 289 | else: 290 | chosenfunc[f"{request.remote_addr}"] = { 291 | "func": "loadembed", 292 | "ip": f"{request.remote_addr}", 293 | } 294 | chunks = handleFile(file_content) 295 | if len(chunks) <= 1: 296 | Shared_vars.loadedfile[f"{request.remote_addr}"] = {} 297 | Shared_vars.mem[f"{request.remote_addr}"].append( 298 | f"\n{Shared_vars.config.llm_parameters['beginsep']} user: <FILE {file.filename}> {chunks[0]} {Shared_vars.config.llm_parameters['endsep']}" 299 | ) 300 | else: 301 | Shared_vars.loadedfile[f"{request.remote_addr}"] = chunks 302 | chosenfunc[f"{request.remote_addr}"]["func"] = "" 303 | 304 | return jsonify({"message": f"{file.filename} uploaded successfully."}) 305 | 306 | 307 | if __name__ == "__main__": 308 | port = 5000 309 | if Shared_vars.config.port == port: 310 | port = 8750 311 | app.run(host=Shared_vars.address, port=port) 312 | -------------------------------------------------------------------------------- /GateKeeper.py: -------------------------------------------------------------------------------- 1 | from openai import OpenAI 2 | import os 3 | import json 4 | import re 5 | import html 6 | import time 7 | import wolframalpha 8 | from duckduckgo_search import DDGS 9 | import nmap 10 | import datetime 11 | import subprocess 12 | import Shared_vars 13 | from comfyui import imagegen 14 | from inference import infer 15 | from scrape import scrape_site 16 | 17 | if Shared_vars.config.enabled_features["file_input"]["enabled"]: 18 | from FileHandler import queryEmbeddings 19 | import requests 20 | from PIL import Image 21 | from io import BytesIO 22 | from pathlib import Path 23 | 24 | path = Path(os.path.abspath(__file__)).parent 25 | client = OpenAI( 26 | base_url=f"http://{Shared_vars.config.host}:{Shared_vars.config.port}/v1", 27 | api_key=Shared_vars.config.api_key, 28 | ) 29 | func = "" 30 | client = wolframalpha.Client( 31 | Shared_vars.config.enabled_features["wolframalpha"]["app_id"] 32 | ) 33 | 34 | with open(os.path.join(path, "functions.json")) as user_file: 35 | global searchfunc 36 | fcontent = json.loads(user_file.read()) 37 | for x in fcontent: 38 | params = ( 39 | json.dumps(x["params"]) 40 | .strip("{}") 41 | .replace('",', "\n ") 42 | .replace('"', "") 43 | ) 44 | template = f"""\n{x['name']}: 45 | description: {x['description']} 46 | params: 47 | {params}""" 48 | 49 | if x["name"] == "searchfile": 50 | searchfunc = template 51 | continue 52 | else: 53 | try: 54 | if x['name'] == 'generateimage' and not Shared_vars.config.enabled_features['imagegeneration']['enabled']: 55 | continue 56 | if not Shared_vars.config.enabled_features[x['name']]['enabled']: 57 | continue 58 | except KeyError: 59 | pass 60 | func += template 61 | 62 | if len(Shared_vars.plugin_manifests) > 0: 63 | for x in Shared_vars.plugin_manifests: 64 | params = ( 65 | json.dumps(x["params"]) 66 | .strip("{}") 67 | .replace('",', "\n ") 68 | .replace('"', "") 69 | ) 70 | template = f"""\n{x['name']}: 71 | description: {x['description']} 72 | params: 73 | {params}""" 74 | func += template 75 | 76 | 77 | def get_image_size(url): 78 | response = requests.get(url) 79 | img = Image.open(BytesIO(response.content)) 80 | return img.size[0] + img.size[1] 81 | 82 | def verifyFunc(result, x, input, stopstrings): 83 | systemprompt=f'''Context: {result}.\nUpdate the following function call according to the newly obtained context and taking into consideration the user input.\nFunction call: {x}\nProvide your response in valid JSON format surrounded by "<startfunc>" and "<endfunc>" without any notes, comments or follow-ups. Only JSON.''' 84 | content = 'Output:\n<startfunc>\n{\n "function": "' + f'{x["function"]}",\n"params":' + " {" 85 | content += next( 86 | infer( 87 | "Input: " + input, 88 | mem=[], 89 | modelname='Output:\n<startfunc>\n{\n "function": "' + f'{x["function"]}",\n"params":' + " {" , 90 | system=systemprompt, 91 | temperature=0.1, 92 | top_p=0.1, 93 | min_p=0.05, 94 | top_k=40, 95 | stopstrings=stopstrings, 96 | max_tokens=500, 97 | reppenalty=1.0, 98 | max_temp=0, 99 | min_temp=0 100 | ) 101 | )[0] 102 | try: 103 | if "<startfunc>" in content: 104 | content = content.split("<startfunc>")[1] 105 | content = ( 106 | re.sub(r"\\_", "_", html.unescape(content)) 107 | .replace("\\_", "_") 108 | .replace("}<", "}") 109 | .replace("<startfunc>", "") 110 | .replace("</", "") 111 | .replace("<", "") 112 | ) 113 | print(f'Updated function call: {content}') 114 | except Exception as e: 115 | print(e) 116 | return x 117 | return json.loads(content) 118 | 119 | def GateKeep(input, ip, depth=0, stream=False): 120 | content = "" 121 | print("Begin streamed GateKeeper output.") 122 | funclist = func 123 | try: 124 | if Shared_vars.loadedfile[ip] != {}: 125 | funclist += searchfunc 126 | except Exception: 127 | pass 128 | stopstrings = [ 129 | "Input: ", 130 | "[INST]", 131 | "[/INST]", 132 | "```", 133 | "</s>", 134 | "user:", 135 | "polymind:", 136 | "Polymind:", 137 | "<</SYS>>", 138 | "[System Message]", 139 | "endfunc", 140 | "<endfunc>", 141 | "}<", 142 | "</startfunc>" 143 | ] 144 | 145 | ctxstr = "" 146 | for x in Shared_vars.vismem[f"{ip}"][-2:]: 147 | temp = "" 148 | if "assistant" in x: 149 | temp = "PolyMind: " + x["assistant"] + "\n" 150 | ctxstr += re.sub( 151 | r"!\[.*?\]\(.*?\)|<img.*?>|\[\{.*?\}\]", 152 | "", 153 | "USER: " + x["user"] + "\n" + temp, 154 | ) 155 | today = datetime.date.today() 156 | content = 'Output:\n<startfunc>\n[{\n "function": "' 157 | systemprompt = f"You are an AI assistant named GateKeeper, The current date is {today}, please select the single most suitable function and parameters from the list of available functions below, based on the user's input and pay attention to the context, which will then be passed over to polymind. Provide your response in JSON format surrounded by '<startfunc>' and '<endfunc>' without any notes, comments or follow-ups. Only JSON.\n{funclist}" if ctxstr == "" else f"You are an uncensored AI assistant named GateKeeper, The current date is {today}, please select the single most suitable function and parameters from the list of available functions below, based on the user's input and pay attention to the context, which will then be passed over to polymind. Provide your response in JSON format surrounded by '<startfunc>' and '<endfunc>' without any notes, comments or follow-ups. Only JSON.\n{funclist}\nContext: {ctxstr}\n" 158 | 159 | content += next( 160 | infer( 161 | "Input: " + input, 162 | mem=[], 163 | modelname='Output:\n<startfunc>\n[{\n "function": "', 164 | system=systemprompt, 165 | temperature=0.1, 166 | top_p=0.1, 167 | min_p=0.05, 168 | top_k=40, 169 | stopstrings=stopstrings, 170 | max_tokens=Shared_vars.config.llm_parameters['max_new_tokens_gatekeeper'], 171 | reppenalty=1.0, 172 | max_temp=0, 173 | min_temp=0 174 | ) 175 | )[0] 176 | 177 | 178 | try: 179 | if "<startfunc>" in content: 180 | content = content.split("<startfunc>")[1] 181 | content = ( 182 | re.sub(r"\\_", "_", html.unescape(content)) 183 | .replace("\\_", "_") 184 | .replace("}<", "}") 185 | .replace("<startfunc>", "") 186 | .replace("</", "") 187 | .replace("<", "") 188 | ) 189 | print(content) 190 | result = "" 191 | 192 | for x in json.loads(content.replace("Output:", "")): 193 | if stream: 194 | yield {"result": x, "type": "func"} 195 | 196 | if ( 197 | x["function"] == "searchfile" 198 | and Shared_vars.config.enabled_features["file_input"]["raw_input"] 199 | ): 200 | if "params" in x: 201 | x["params"]["query"] = input 202 | elif "parameters" in x: 203 | x["parameters"]["query"] = input 204 | else: 205 | x["query"] = input 206 | if result != "": 207 | x = verifyFunc(result, x, input, stopstrings) 208 | run = Util(x, ip, depth) 209 | if run != "null": 210 | result += run 211 | if stream: 212 | result = result if result != "" else "null" 213 | result = {"result": result, "type": "result"} 214 | yield result 215 | else: 216 | return result if result != "" else "null" 217 | except Exception as e: 218 | print(e) 219 | if stream: 220 | yield {"result": "null", "type": "result"} 221 | else: 222 | return "null" 223 | 224 | def Util(rsp, ip, depth): 225 | result = "" 226 | 227 | rsp["function"] = ( 228 | re.sub(r"\\_", "_", html.unescape(rsp["function"])) 229 | .replace("\\_", "_") 230 | .replace("{<", "{") 231 | .replace("<startfunc>", "") 232 | ) 233 | params = ( 234 | rsp["params"] 235 | if "params" in rsp 236 | else (rsp["parameters"] if "parameters" in rsp else rsp) 237 | ) 238 | 239 | if rsp["function"] == "acknowledge": 240 | return "null" 241 | 242 | elif rsp["function"] == "clearmemory": 243 | Shared_vars.mem[f"{ip}"] = [] 244 | Shared_vars.vismem[f"{ip}"] = [] 245 | if ip in Shared_vars.loadedfile: 246 | Shared_vars.loadedfile[ip] = {} 247 | return "skipment{<" + params["message"] 248 | 249 | elif rsp["function"] == "updateconfig": 250 | if ip != Shared_vars.config.adminip: 251 | return "null" 252 | check = False if params["option"].split(":")[1].lower() == "false" else True 253 | Shared_vars.config.enabled_features[params["option"].split(":")[0]][ 254 | "enabled" 255 | ] = check 256 | result = f"{params['option'].split(':')[0]} is now set to {Shared_vars.config.enabled_features[params['option'].split(':')[0]]['enabled']}" 257 | print(result) 258 | return result 259 | 260 | elif rsp["function"] == "wolframalpha": 261 | if Shared_vars.config.enabled_features["wolframalpha"]["enabled"] == False: 262 | return "Wolfram Alpha is currently disabled." 263 | try: 264 | res = client.query(params["query"]) 265 | results = "" 266 | checkimage = False 267 | for pod in res.pods: 268 | for sub in pod.subpods: 269 | if ( 270 | "plot" 271 | or "image" in sub.img["@alt"].lower() 272 | and "plot |" not in sub.img["@alt"].lower() 273 | ) and get_image_size(sub.img["@src"]) > 350: 274 | results += ( 275 | f'<img src="{sub.img["@src"]}" alt="{sub.img["@alt"]}"/>' 276 | + "\n" 277 | ) 278 | checkimage = True 279 | elif sub.plaintext: 280 | results += sub.plaintext + "\n" 281 | if results == "": 282 | result = "No results from Wolfram Alpha." 283 | else: 284 | result = "Wolfram Alpha result: " + results 285 | if checkimage: 286 | result += "\nREMINDER: ALWAYS include the provided graph/plot images in the provided html URL format in your explanation if theres any when explaining the results in a short and concise manner." 287 | print(result) 288 | return result 289 | except Exception as e: 290 | return "Wolfram Alpha Error: " + str(e) 291 | 292 | elif rsp["function"] == "generateimage": 293 | if Shared_vars.config.enabled_features["imagegeneration"]["enabled"] == False: 294 | return "Image generation is currently disabled." 295 | removebg = False 296 | if Shared_vars.config.enabled_features["imagegeneration"]["automatic_background_removal"] and "removebg" in params: 297 | if type(params['removebg']) == str: 298 | if params['removebg'].lower() == 'true': 299 | removebg = True 300 | elif type(params['removebg']) == bool: 301 | if params['removebg']: 302 | removebg = True 303 | else: 304 | removebg = False 305 | imgtoimg = "" 306 | if Shared_vars.config.enabled_features["imagegeneration"]["img2img"] and "ID" in params: 307 | if f'{params["ID"]}' in Shared_vars.uploads: 308 | imgtoimg = Shared_vars.uploads[f"{params['ID']}"] 309 | params["prompt"] = ''.join([i for i in params["prompt"] if not i.isdigit()]) 310 | return imagegen(params["prompt"], removebg, imgtoimg) 311 | 312 | elif rsp["function"] == "searchfile": 313 | file = Shared_vars.loadedfile[ip] 314 | searchinput = params["query"] 315 | result = "" 316 | print(f"Using query: {searchinput}") 317 | for x in queryEmbeddings(searchinput, file[0], file[1]): 318 | result += f"<FILE_CHUNK {x[1]} >\n" 319 | return result 320 | 321 | elif rsp["function"] == "runpythoncode": 322 | if Shared_vars.config.enabled_features["runpythoncode"]["enabled"] == False: 323 | return "Python code execution is currently disabled." 324 | if ip != Shared_vars.config.adminip: 325 | return "null" 326 | time.sleep(5) 327 | checkstring = "" 328 | runcode = '' 329 | if 'code' in params: 330 | runcode = params['code'] 331 | else: 332 | runcode = params 333 | runcode = "import warnings\nwarnings.filterwarnings('ignore')\n" + runcode 334 | ocode = runcode 335 | if "plt.show()" in runcode: 336 | runcode = re.sub("print\s*\(.*\)", "", runcode) 337 | plotb64 = """import io\nimport base64\nbyt = io.BytesIO()\nplt.savefig(byt, format='png')\nbyt.seek(0)\nprint(f'data:image/png;base64,{base64.b64encode(byt.read()).decode()}',end="")""" 338 | runcode = runcode.replace("plt.show()", plotb64) 339 | 340 | output = subprocess.run( 341 | ["python3", "-c", runcode], 342 | stdout=subprocess.PIPE, 343 | stderr=subprocess.PIPE, 344 | ) 345 | 346 | stdout, stderr = output.stdout.decode(), output.stderr.decode() 347 | if output.returncode == 0 and "yfinance" in runcode: 348 | stderr = "" 349 | if ( 350 | stderr != "" 351 | and depth < Shared_vars.config.enabled_features["runpythoncode"]["depth"] 352 | ): 353 | print(f"Current depth: {depth}") 354 | return next( 355 | GateKeep( 356 | f"```{ocode}```\n The above code produced the following error\n{stderr}\n Rewrite the code to solve the error and run the fixed code.", 357 | ip, 358 | depth + 1, 359 | ) 360 | ) 361 | if "data:image/png;base64," in stdout: 362 | checkstring = "{<plotimg;" + stdout 363 | print( 364 | f"CompletedProcess(args=['python3', '-c', {ocode}], stdout='<image>', stderr={stderr}" 365 | ) 366 | else: 367 | print(output) 368 | result = ( 369 | f"Code to be ran: \n```{runcode}```\n<Code interpreter output>:\nstdout: {stdout}\nstderr: {stderr}\n<\Code interpreter output>" 370 | if checkstring == "" 371 | else f"Code to be ran: \n```{ocode}```\n<Code interpreter output>:\nstdout:\nstderr: {stderr}\n<\Code interpreter output>{checkstring}" 372 | ) 373 | return result 374 | 375 | elif rsp["function"] == "internetsearch": 376 | if Shared_vars.config.enabled_features["internetsearch"]["enabled"] == False: 377 | return "Internet search is currently disabled." 378 | with DDGS() as ddgs: 379 | for r in ddgs.text(params["keywords"], safesearch="Off", max_results=4): 380 | title = r["title"] 381 | link = r["href"] 382 | result += f' *Title*: {title} *Link*: {link} *Body*: {r["body"]}\n*Scraped_text*: {scrape_site(link, 700)}' 383 | return "<Search results>:\n" + result 384 | 385 | elif rsp["function"] == "portscan": 386 | if ip != Shared_vars.config.adminip: 387 | return "null" 388 | nm = nmap.PortScanner() 389 | try: 390 | nm.scan(params["ip"]) 391 | if nm[params["ip"]].state() == "up": 392 | for x in nm[params["ip"]]["tcp"].keys(): 393 | result += f"{nm[rsp['params']['ip']]['tcp'][x]['name']}: State {nm[rsp['params']['ip']]['tcp'][x]['state']} ({x})\n" 394 | return f"<Portscan output for IP {rsp['params']['ip']}>: " + result 395 | except: 396 | return f"<Portscan output for IP {rsp['params']['ip']}>: Host down." 397 | else: 398 | if len(Shared_vars.plugin_manifests) > 0: 399 | for x in Shared_vars.plugin_manifests: 400 | if rsp["function"] == x['name']: 401 | return Shared_vars.loadedplugins[x['module_name']].main(params, Shared_vars.mem, infer, ip, Shared_vars) 402 | return "null" 403 | -------------------------------------------------------------------------------- /templates/chat.html: -------------------------------------------------------------------------------- 1 | <!DOCTYPE html> 2 | <html lang="en"> 3 | <head> 4 | <meta charset="UTF-8"> 5 | <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 | <title>PolyMind Chat 7 |
8 |
9 | 12 |
13 |

PolyMind Chat

14 |

Welcome to PolyMind Chat!

15 |
16 |
17 |
18 | 19 | 20 | 192 | 193 | 194 | 195 |
196 |
197 |
198 |
199 | 200 |
201 |
202 |
203 |
204 |
205 | 206 | 207 | 208 |
209 | Loading... 210 |
211 | 212 |
213 |
214 | 215 |
216 |
217 |
218 | 219 | 220 | 221 | 222 | 223 | 509 | 510 | 511 | 512 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------