[
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Microsoft Open Source Code of Conduct\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\n\nResources:\n\n- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)\n- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)\n- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "\nTo contribute to this GitHub project, you can follow these steps:\n\n1. Fork the repository you want to contribute to by clicking the \"Fork\" button on the project page.\n\n2. Clone the repository to your local machine and enter the newly created repo using the following commands:\n\n```\ngit clone https://github.com/YOUR-GITHUB-USERNAME/TaskMatrix.git\ncd TaskMatrix\n```\n3. Create a new branch for your changes using the following command:\n\n```\ngit checkout -b \"branch-name\"\n```\n4. Make your changes to the code or documentation.\n\n5. Add the changes to the staging area using the following command:\n```\ngit add . \n```\n\n6. Commit the changes with a meaningful commit message using the following command:\n```\ngit commit -m \"your commit message\"\n```\n7. Push the changes to your forked repository using the following command:\n```\ngit push origin branch-name\n```\n8. Go to the GitHub website and navigate to your forked repository.\n\n9. Click the \"New pull request\" button.\n\n10. Select the branch you just pushed to and the branch you want to merge into on the original repository.\n\n11. Add a description of your changes and click the \"Create pull request\" button.\n\n12. Wait for the project maintainer to review your changes and provide feedback.\n\n13. Make any necessary changes based on feedback and repeat steps 5-12 until your changes are accepted and merged into the main project.\n\n14. Once your changes are merged, you can update your forked repository and local copy of the repository with the following commands:\n\n```\ngit fetch upstream\ngit checkout main\ngit merge upstream/main\n```\nFinally, delete the branch you created with the following command:\n```\ngit branch -d branch-name\n```\nThat's it you made it 🐣⭐⭐"
  },
  {
    "path": "LICENSE.txt",
    "content": "MIT License\n\nCopyright (c) 2023 Microsoft\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\nThe recommended models in this Repo are just examples, used for scientific research exploring the concept of task automation and benchmarking with the paper published at [Visual ChatGPT: Talking, Drawing and Editing with Visual Foundation Models](https://arxiv.org/abs/2303.04671). Users can replace the models in this Repo according to their research needs. When using the recommended models in this Repo, you need to comply with the licenses of these models respectively. Microsoft shall not be held liable for any infringement of third-party rights resulting from your usage of this repo. Users agree to defend, indemnify and hold Microsoft harmless from and against all damages, costs, and attorneys' fees in connection with any claims arising from this Repo. If anyone believes that this Repo infringes on your rights, please notify the project owner [email](chewu@microsoft.com).\n"
  },
  {
    "path": "LowCodeLLM/Dockerfile",
    "content": "FROM ubuntu:22.04\r\n\r\nRUN apt-get -y update\r\nRUN apt-get install -y git python3.11 python3-pip supervisor\r\nRUN pip3 install --upgrade pip\r\nRUN pip3 install --upgrade setuptools\r\nRUN ln -s /usr/bin/python3 /usr/bin/python\r\nCOPY src/requirements.txt requirements.txt\r\nRUN pip3 install -r requirements.txt\r\n\r\nCOPY src /app/src\r\n\r\nWORKDIR /app/src\r\nENV WORKERS 2\r\nCMD supervisord -c supervisord.conf\r\n"
  },
  {
    "path": "LowCodeLLM/README.md",
    "content": "# Low-code LLM\n\n**Low-code LLM** is a novel human-LLM interaction pattern, involving human in the loop to achieve more controllable and stable responses.\n\nSee our paper: [Low-code LLM: Visual Programming over LLMs](https://arxiv.org/abs/2304.08103)\n\nIn the future, [TaskMatrix.AI](https://arxiv.org/abs/2304.08103) can enhance task automation by breaking down tasks more effectively and utilizing existing foundation models and APIs of other AI models and systems to achieve diversified tasks in both digital and physical domains. And the low-code human-LLM interaction pattern can enhance user's experience on controling over the process and expressing their preference.\n\n## Video Demo\nhttps://user-images.githubusercontent.com/43716920/233937121-cd057f04-dec8-45b8-9c52-a9e9594eec80.mp4\n\n(This is a conceptual video demo to demonstrate the complete process)\n\n## Quick Start\nPlease note that due to time constraints, the code we provide is only the minimum viable version of the low-code LLM interactive code, i.e. only demonstrating the core concept of Low-code LLM human-LLM interaction. We welcome anyone who is interested in improving our front-end interface.\nCurrently, both the `OpenAI API` and `Azure OpenAI Service` are supported. You would be required to provide the requisite information to invoke these APIs.\n\n```\n# clone the repo\ngit clone https://github.com/microsoft/TaskMatrix.git\n\n# go to directlory\ncd LowCodeLLM\n\n# build and run docker\ndocker build -t lowcode:latest .\n\n# If OpenAI API is being used, it is only necessary to provide the API key.\ndocker run -p 8888:8888 --env OPENAIKEY={Your_Private_Openai_Key} lowcode:latest\n\n# When using Azure OpenAI Service, it is advisable to store the necessary information in a configuration file for ease of access.\n# Kindly duplicate the config.template file and name the copied file as config.ini. Then, fill out the necessary information in the config.ini file.\ndocker run -p 8888:8888 --env-file config.ini lowcode:latest\n```\nYou can now try it by visiting [Demo page](http://localhost:8888/)\n\n\n## System Overview\n\n<img src=\"https://github.com/microsoft/TaskMatrix/blob/main/assets/low-code-llm.png\" alt=\"overview\" width=\"800\"/>\n\nAs shown in the above figure, human-LLM interaction can be completed by:\n- A Planning LLM that generates a highly structured workflow for complex tasks.\n- Users editing the workflow with predefined low-code operations, which are all supported by clicking, dragging, or text editing. \n- An Executing LLM that generates responses with the reviewed workflow. \n- Users continuing to refine the workflow until satisfactory results are obtained.\n\n## Six Kinds of Pre-defined Low-code Operations\n<img src=\"https://github.com/microsoft/TaskMatrix/blob/main/assets/low-code-operation.png\" alt=\"operations\" width=\"800\"/>\n\n## Advantages\n\n- **Controllable Generation.** Complicated tasks are decomposed into structured conducting plans and presented to users as workflows. Users can control the LLMs’ execution through low-code operations to achieve more controllable responses. The responses generated followed the customized workflow will be more aligned with the user’s requirements.\n- **Friendly Interaction.** The intuitive workflow enables users to swiftly comprehend the LLMs' execution logic, and the low-code operation through a graphical user interface empowers users to conveniently modify the workflow in a user-friendly manner. In this way, time-consuming prompt engineering is mitigated, allowing users to efficiently implement their ideas into detailed instructions to achieve high-quality results.\n- **Wide applicability.** The proposed framework can be applied to a wide range of complex tasks across various domains, especially in situations where human's intelligence or preference are indispensable.\n\n\n## Acknowledgement\nPart of this paper has been collaboratively crafted through interactions with the proposed Low-code LLM. The process began with GPT-4 outlining the framework, followed by the authors supplementing it with innovative ideas and refining the structure of the workflow. Ultimately, GPT-4 took charge of generating cohesive and compelling text.\n"
  },
  {
    "path": "LowCodeLLM/config.template",
    "content": "USE_AZURE=True\r\nOPENAIKEY=your-azure-openai-service-key\r\nAPI_BASE=your-base-url-for-azure\r\nAPI_VERSION=2023-03-15-preview\r\nMODEL=your-gpt-deployment-name"
  },
  {
    "path": "LowCodeLLM/src/app.py",
    "content": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport os\r\nfrom flask import Flask, request, send_from_directory\r\nfrom flask_cors import CORS, cross_origin\r\nfrom lowCodeLLM import lowCodeLLM\r\nfrom flask.logging import default_handler\r\nimport logging\r\n\r\napp = Flask('lowcode-llm', static_folder='', template_folder='')\r\napp.debug = True\r\nllm = lowCodeLLM()\r\ngunicorn_logger = logging.getLogger('gunicorn.error')\r\napp.logger = gunicorn_logger\r\nlogging_format = logging.Formatter(\r\n    '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')\r\ndefault_handler.setFormatter(logging_format)\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n    return send_from_directory(\".\", \"index.html\")\r\n\r\n@app.route('/api/get_workflow', methods=['POST'])\r\n@cross_origin()\r\ndef get_workflow():\r\n    try:\r\n        request_content = request.get_json()\r\n        task_prompt = request_content['task_prompt']\r\n        workflow = llm.get_workflow(task_prompt)\r\n        return workflow, 200\r\n    except Exception as e:\r\n        app.logger.error(\r\n            'failed to get_workflow, msg:%s, request data:%s' % (str(e), request.json))\r\n        return {'errmsg': 'internal errors'}, 500\r\n\r\n@app.route('/api/extend_workflow', methods=['POST'])\r\n@cross_origin()\r\ndef extend_workflow():\r\n    try:\r\n        request_content = request.get_json()\r\n        task_prompt = request_content['task_prompt']\r\n        current_workflow = request_content['current_workflow']\r\n        step = request_content['step']\r\n        sub_workflow = llm.extend_workflow(task_prompt, current_workflow, step)\r\n        return sub_workflow, 200\r\n    except Exception as e:\r\n        app.logger.error(\r\n            'failed to extend_workflow, msg:%s, request data:%s' % (str(e), request.json))\r\n        return {'errmsg': 'internal errors'}, 500\r\n\r\n@app.route('/api/execute', methods=['POST'])\r\n@cross_origin()\r\ndef execute():\r\n    try:\r\n        request_content = request.get_json()\r\n        task_prompt = request_content['task_prompt']\r\n        confirmed_workflow = request_content['confirmed_workflow']\r\n        curr_input = request_content['curr_input']\r\n        history = request_content['history']\r\n        response = llm.execute(task_prompt,confirmed_workflow, history, curr_input)\r\n        return response, 200\r\n    except Exception as e:\r\n        app.logger.error(\r\n            'failed to execute, msg:%s, request data:%s' % (str(e), request.json))\r\n        return {'errmsg': 'internal errors'}, 500\r\n"
  },
  {
    "path": "LowCodeLLM/src/executingLLM.py",
    "content": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nfrom openAIWrapper import OpenAIWrapper\r\n\r\nEXECUTING_LLM_PREFIX = \"\"\"Executing LLM is designed to provide outstanding responses.\r\nExecuting LLM will be given a overall task as the background of the conversation between the Executing LLM and human.\r\nWhen providing response, Executing LLM MUST STICTLY follow the provided standard operating procedure (SOP).\r\nthe SOP is formatted as:\r\n'''\r\nSTEP 1: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\r\n'''\r\nhere \"[[[if 'condition1'][Jump to STEP n]]]\" is judgmental logic. It means when you're performing this step, and if 'condition1' is satisfied, you will perform STEP n next.\r\n\r\nRemember: \r\nExecuting LLM is facing a real human, who does not know what SOP is. \r\nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\r\n\"\"\"\r\n\r\nEXECUTING_LLM_SUFFIX = \"\"\"\r\nRemember: \r\nExecuting LLM is facing a real human, who does not know what SOP is. \r\nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\r\n\"\"\"\r\n\r\nclass executingLLM:\r\n    def __init__(self, temperature) -> None:\r\n        self.prefix = EXECUTING_LLM_PREFIX\r\n        self.suffix = EXECUTING_LLM_SUFFIX\r\n        self.LLM = OpenAIWrapper(temperature)\r\n        self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\r\n                         {\"role\": \"system\", \"content\": self.prefix}]\r\n\r\n    def execute(self, current_prompt, history):\r\n        ''' provide LLM the dialogue history and the current prompt to get response '''\r\n        messages = self.messages + history\r\n        messages.append({'role': 'user', \"content\": current_prompt + self.suffix})\r\n        response, status = self.LLM.run(messages)\r\n        if status:\r\n            return response\r\n        else:\r\n            return \"OpenAI API error.\""
  },
  {
    "path": "LowCodeLLM/src/index.html",
    "content": "<!-- Copyright (c) Microsoft Corporation.\r\n     Licensed under the MIT License. -->\r\n     \r\n<!DOCTYPE html>\r\n<html lang=\"en\">\r\n  <head>\r\n    <meta charset=\"UTF-8\" />\r\n    <title>Tutorial Demo</title>\r\n    <style>\r\n      h1{\r\n        text-align: center;\r\n      }\r\n      #container{\r\n        display: flex;\r\n        flex: 1;\r\n      }\r\n      #prompt-container{\r\n        width: 800px;\r\n      }\r\n      .mountNodeContainer{\r\n        position: relative;\r\n      }\r\n      #mountNodeLoading{\r\n        display: none;\r\n        position: absolute;\r\n        width: 100%;\r\n        height: 100%;\r\n        top: 0;\r\n        left: 0;\r\n        background: rgba(0,0,0,0.8);\r\n        text-align: center;\r\n        padding-top: 50px;\r\n        color: white;\r\n        box-sizing: border-box;\r\n      }\r\n      #mountNode{\r\n        margin-top: 50px;\r\n        position: relative;\r\n        width: 800px;\r\n        height: 750px;\r\n      }\r\n      #mountNode canvas{\r\n        background-color: antiquewhite;\r\n      }\r\n      #dia-container{\r\n        margin: 0 30px;\r\n        border: 1px solid black;\r\n        width: 600px;\r\n        height: 870px;\r\n        padding: 10px;\r\n      }\r\n      #dialogues{\r\n        height: 835px;\r\n        width: 100%;\r\n        overflow-y: scroll\r\n      }\r\n\r\n      #contextMenu {\r\n        position: absolute;\r\n        list-style-type: none;\r\n        padding: 10px 8px;\r\n        left: -150px;\r\n        background-color: rgba(255, 255, 255, 0.9);\r\n        border: 1px solid #e2e2e2;\r\n        border-radius: 4px;\r\n        font-size: 12px;\r\n        color: #545454;\r\n      }\r\n      #contextMenu li {\r\n        cursor: pointer;\r\n        list-style-type:none;\r\n        list-style: none;\r\n        margin-left: 0px;\r\n      }\r\n      #contextMenu li:hover {\r\n        color: #aaa;\r\n      }\r\n      .dia-me{\r\n        margin: 10px;\r\n        margin-left: 50px;\r\n        padding: 5px;\r\n        border: 1px solid blue;\r\n        text-align: right;\r\n      }\r\n      .dia-ai{\r\n        margin: 10px;\r\n        margin-right: 50px;\r\n        padding: 5px;\r\n        border: 1px solid red;\r\n      }\r\n    </style>\r\n  </head>\r\n  <body>\r\n    <h1>Low Code Demo</h1>\r\n    <div id=\"container\">\r\n      <div id=\"left\">\r\n        <div id=\"prompt-container\">\r\n          Task:\r\n          <br/>\r\n          <input id=\"prompt-text\" type=\"text\" placeholder=\"type your task here \"size=\"50\">\r\n          <button id=\"prompt-confirm\" onclick=\"promptConfirm()\">Confirm</button>\r\n        </div>\r\n        <div class=\"mountNodeContainer\">\r\n          <div id=\"mountNode\"></div>\r\n          <div id=\"mountNodeLoading\">loading...</div>\r\n        </div>\r\n        <button id=\"regenerate\" onclick=\"promptConfirm()\">Regenerate</button>\r\n        <!-- <button id=\"workflow-Confirm\" onclick=\"workflowConfirm()\">Confirm</button> -->\r\n      </div>\r\n      <div id=\"right\">\r\n        <div id=\"dia-container\">\r\n          <div id=\"dialogues\"></div>\r\n          <input id=\"message-text\" type=\"text\" placeholder=\"type your question here\" size=\"70\">\r\n          <button id=\"dia-confirm\" onclick=\"diaConfirm()\">Send</button>\r\n        </div>\r\n      </div>\r\n    </div>\r\n    \r\n\r\n    <script src=\"https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.7.1/dist/g6.min.js\"></script>\r\n    <script src=\"https://unpkg.com/axios/dist/axios.min.js\"></script>\r\n    <script>\r\n\r\n      function dataToG6(oriData, parent, color){\r\n        let nodes = [];\r\n        let edges = [];\r\n        let polylineLength = graph.save().edges.filter((edge)=>{\r\n          return edge.type === \"polyline\"\r\n        }).length+1\r\n        for (let index = 0; index < oriData.length; index++) {\r\n          const item = oriData[index];\r\n          let label = \"\";\r\n          if (item.stepDescription.length > 50){\r\n            label = item.stepDescription.substring(0, 50) + \"-\\n\" + item.stepDescription.substring(50)\r\n          } else{\r\n            label = item.stepDescription\r\n          }\r\n           \r\n          let n = {\r\n            id: item.stepId,\r\n            type: 'rect',\r\n            extension: []\r\n          };\r\n          n.label = n.id + item.stepName + '\\n' + label;\r\n          nodes.push(n);\r\n          if (item.jumpLogic.length > 0){\r\n            let jumpLogic = item.jumpLogic\r\n            for (let j = 0; j < jumpLogic.length; j++){\r\n              let e = {\r\n                source: item.stepId, // start id\r\n                target: jumpLogic[j].Target, // target id\r\n                label: jumpLogic[j].Condition, // jump condition text\r\n                type:\"polyline\",\r\n                style: {\r\n                  opacity: 0.6,\r\n                  stroke: '#f00',\r\n                  offset: (polylineLength)*20,\r\n                  endArrow: {\r\n                    path: G6.Arrow.vee(15, 20, 0), // arrows\r\n                    d: 0\r\n                  }, \r\n                },\r\n                sourceAnchor:3,\r\n                targetAnchor:3\r\n              }\r\n              edges.push(e);\r\n              polylineLength +=1\r\n            }\r\n          }\r\n          if(index > 0){\r\n            let e = {\r\n                source: oriData[index-1].stepId, // start id\r\n                target: item.stepId, // target id\r\n                label: '', // jump condition text\r\n                type:\"line\",\r\n              }\r\n              edges.push(e);\r\n          }\r\n        }\r\n        console.log(nodes,edges)\r\n        return {\r\n          nodes,\r\n          edges,\r\n        }\r\n      }\r\n\r\n      function G6ToData(){\r\n        let nodes = graph.getNodes();\r\n        let data = [];\r\n        let edges = graph.getEdges();\r\n        for (const n of nodes) {\r\n          let id = n.getID();\r\n          let label = n.getModel().label;\r\n          let strs = label.split('\\n');\r\n          let name = strs[0].substring(id.length);\r\n          let des = \"\";\r\n          if(strs.length == 2){\r\n            des = strs[1]\r\n          } else {\r\n            des = strs[1].substring(0, strs[1].length - 1) + strs[2]\r\n          }\r\n          let o = {\r\n            stepId: id,\r\n            stepName: name,\r\n            stepDescription: des,\r\n            jumpLogic: [],\r\n            extension: []\r\n          }\r\n          data.push(o)\r\n        }\r\n        for (const e of edges) {\r\n          let label = e.getModel().label;\r\n          if(label === '')\r\n            continue;\r\n          let source = e.getModel().source;\r\n          let target = e.getModel().target;\r\n          let o = {\r\n            Condition: label, \r\n            Target: target\r\n          }\r\n          for (const n of data){\r\n            if(n.stepId === source){\r\n              n.jumpLogic.push(o);\r\n              break;\r\n            }\r\n          }\r\n        }\r\n\r\n        for (const n of data){\r\n          let sub = n.stepId.split('.');\r\n          if(sub.length === 1){\r\n            continue;\r\n          } else {\r\n            let parentNode;\r\n            for (const p of data){\r\n              if(p.stepId === sub[0]){\r\n                parentNode = p;\r\n                break;\r\n              }\r\n            }\r\n            for(let i = 1; i < sub.length - 1; i ++){\r\n              parentNode = parentNode.extension[parseInt(sub[i])]\r\n            }\r\n            parentNode.extension.push(JSON.parse(JSON.stringify(n)));\r\n            n.flag = true;\r\n          }\r\n        }\r\n\r\n        for (let i = data.length - 1; i >= 0; i --){\r\n          if(data[i].flag === true)\r\n            data.splice(i, 1)\r\n        }\r\n\r\n        return JSON.stringify(data, null, 2);\r\n      }\r\n\r\n      function update() {\r\n        const nodes = graph.getNodes();\r\n        console.log(nodes)\r\n      }\r\n      const contextMenu = new G6.Menu({\r\n        getContent(evt) {\r\n          let header;\r\n          if (evt.target && evt.target.isCanvas && evt.target.isCanvas()) {\r\n            header = 'Canvas ContextMenu';\r\n          } else if (evt.item) {\r\n            const itemType = evt.item.getType();\r\n            header = `${itemType.toUpperCase()} Operation`;\r\n          }\r\n          return `\r\n          <h3>${header}</h3>\r\n          <ul>\r\n            <li id=\"add\">Add</li>\r\n            <li id=\"delete\">Delete</li>\r\n            <li id=\"edit\">Edit</li>\r\n            <li id=\"moveup\">Move Forward</li>\r\n            <li id=\"extend\">Extend</li>\r\n            <li id=\"addcondition\">Add Condition</li>\r\n          </ul>`;\r\n        },\r\n        handleMenuClick: (target, item) => {\r\n          const graphData = graph.save()\r\n          let nodes = graphData.nodes\r\n          let edges = graphData.edges\r\n          const model = item.getModel();\r\n          clickedModelId = model.id;\r\n\r\n          if (target.id === \"add\") {\r\n            const nodeIndex = nodes.findIndex((node)=>node.id === clickedModelId)\r\n            const edgeIndex = edges.findIndex((edge)=>{\r\n              return edge.source === clickedModelId && (!edge.type||edge.type ===\"line\")\r\n            })\r\n            const id = \"STEP \" + (nodeIndex+2) // \"ADD-\"+Date.now()\r\n            const nodeModel = {\r\n              id: id,\r\n              type: 'rect',\r\n            };\r\n            nodeModel.label = nodeModel.id + \" STEP Name\" + \"\\n\" +  \"STEP Description\";\r\n            edges = edges.map((e)=>{\r\n              const sourceNum = Number(e.source.slice(5))||edges.length\r\n              const targetNum = Number(e.target.slice(5))||edges.length\r\n              return {\r\n                ...e,\r\n                source: sourceNum>nodeIndex+1?e.source.slice(0,5) + (sourceNum+1):e.source, \r\n                target: targetNum>nodeIndex+1?e.target.slice(0,5) + (targetNum+1):e.target, \r\n              }\r\n            })\r\n            const edgeModel = {\r\n              source: '', // start id\r\n              target: \"\", // target id\r\n              label: '', // jump condition text\r\n              type:'line'\r\n            };\r\n            if(edgeIndex>=0){\r\n              edgeModel.source = id\r\n              edgeModel.target = edges[edgeIndex].target\r\n              edges[edgeIndex].target = id;\r\n              edges.splice(edgeIndex+1,0,edgeModel);\r\n            }else{\r\n              edgeModel.source = nodes[nodes.length-1].id\r\n              edgeModel.target = id\r\n              edges.push(edgeModel)\r\n            }\r\n            if(nodeIndex>=0)nodes.splice(nodeIndex+1,0,nodeModel);\r\n            nodes = nodes.map((n,i)=>{\r\n              if(i>nodeIndex+1){\r\n                const id = \"STEP \" + (i+1)\r\n                return {\r\n                  ...n,\r\n                  id,\r\n                  label:n.label.replaceAll(n.id,id)\r\n                }\r\n              }\r\n              return n\r\n            })\r\n            console.log(nodes,edges)\r\n            graph.read({\r\n              nodes,edges\r\n            })\r\n          } else if(target.id === \"delete\"){\r\n            const nodeIndex = nodes.findIndex((node)=>node.id === clickedModelId)\r\n            let clickedModelTargetId = \"\"\r\n            edges = edges.filter((edge,i)=>{\r\n              if(edge.type ===\"polyline\" && (edge.source===clickedModelId||edge.target===clickedModelId)){\r\n                return false\r\n              }\r\n              if(edge.source === clickedModelId){\r\n                clickedModelTargetId = edge.target\r\n                return false\r\n              }\r\n              if(edge.target === clickedModelId&&i===edges.length-1){\r\n                return false\r\n              }\r\n              return true\r\n            }).map((e)=>{\r\n              const sourceNum = Number(e.source.slice(5))||edges.length\r\n              const targetNum = e.target === clickedModelId?(Number(clickedModelTargetId.slice(5))||edges.length):(Number(e.target.slice(5))||edges.length)\r\n              return {\r\n                ...e,\r\n                source: sourceNum>=nodeIndex+1?e.source.slice(0,5) + (sourceNum-1):e.source, \r\n                target: targetNum>=nodeIndex+1?e.target.slice(0,5) + (targetNum-1):e.target, \r\n              }\r\n            })\r\n            if(nodeIndex>=0)nodes.splice(nodeIndex,1)\r\n            nodes = nodes.map((n,i)=>{\r\n              if(i>=nodeIndex){\r\n                const id = \"STEP \" + (i+1)\r\n                return {\r\n                  ...n,\r\n                  id,\r\n                  label:n.label.replaceAll(n.id,id)\r\n                }\r\n              }\r\n              return n\r\n            })\r\n            console.log(nodes,edges)\r\n            graph.read({\r\n              nodes,edges\r\n            })\r\n          }else if(target.id === \"edit\"){\r\n            let p = prompt(\"Please Edit STEP\", item.getModel().label);\r\n            const model = {\r\n              id: item.getID(),\r\n              label: p,\r\n            };\r\n            graph.updateItem(item, model);\r\n          }else if(target.id === \"moveup\"){\r\n            const nodeIndex = nodes.findIndex((node)=>node.id === clickedModelId)\r\n            if(nodeIndex>0){\r\n              const v1 = nodes[nodeIndex]\r\n              const v2 = nodes[nodeIndex-1]\r\n              nodes[nodeIndex] = {...v2,id:v1.id,label:v2.label.replaceAll(v2.id,v1.id)}\r\n              nodes[nodeIndex-1] = {...v1,id:v2.id,label:v1.label.replaceAll(v1.id,v2.id)}\r\n            }\r\n            console.log(nodes,edges)\r\n            graph.read({\r\n              nodes,edges\r\n            })\r\n          }else if(target.id === \"extend\"){\r\n            let data = JSON.stringify({\r\n              \"task_prompt\": document.getElementById(\"prompt-text\").value,\r\n              \"current_workflow\": G6ToData(),\r\n              \"step\": item.getID()\r\n            });\r\n            axios.post(\"http://127.0.0.1:8888/api/extend_workflow\", data, {\r\n              headers: {\"Content-Type\": \"application/json\"}\r\n            })\r\n            .then(response => {\r\n              extendData = response.data;\r\n              const currData = JSON.parse(G6ToData())\r\n              const nodeIndex = nodes.findIndex((node)=>node.id === clickedModelId)\r\n              if(currData[nodeIndex]&&extendData.length>0){\r\n                extendData[extendData.length-1].jumpLogic.push(...currData[nodeIndex].jumpLogic)\r\n              }\r\n              currData.splice(nodeIndex,1,...extendData)\r\n              addedData = currData.map((data,i)=>{\r\n                if(i>=nodeIndex){\r\n                  const stepId = \"STEP \" + (i+1)\r\n                  return {\r\n                    ...data,\r\n                    stepId,\r\n                    jumpLogic:data.jumpLogic.map((j)=>{\r\n                      const num = Number(j.Target.slice(5))||currData.length\r\n                      if(num>nodeIndex+1){\r\n                        const newNum = (num+extendData.length-1)\r\n                        return {\r\n                          ...j,\r\n                          Target:\"STEP \" + (newNum>0?newNum:\"\")\r\n                        }\r\n                      }\r\n                      return j\r\n                    })\r\n                  }\r\n                }\r\n                return data\r\n              })\r\n              const {nodes:extendNodes,edges:extendEdges} = dataToG6(addedData)\r\n              graph.read({\r\n                nodes:extendNodes,edges:extendEdges\r\n              })\r\n            })\r\n            .catch(error => {\r\n              alert(\"Network error, please try again.\")\r\n              console.error(error);\r\n            });\r\n\r\n          }else if(target.id === \"addcondition\"){\r\n            let id = prompt(\"Plese Enter NodeID (e.g., STEP 1)\");\r\n            node = graph.findById(id);\r\n            if(!node){\r\n              alert(\"No Such Node\")\r\n              return;\r\n            }\r\n            let c = prompt(\"Please Enter Condition\");\r\n            const polylineLength = graph.save().edges.filter((edge)=>{\r\n              return edge.type === \"polyline\"\r\n            }).length\r\n            const model = {\r\n              source: item.getID(), // start id\r\n              target: id, // target id\r\n              label: c, // jump condition text\r\n              type:\"polyline\",\r\n              style: {\r\n                opacity: 0.6,\r\n                stroke: '#f00',\r\n                offset: (polylineLength+1)*20,\r\n                endArrow: {\r\n                  path: G6.Arrow.vee(15, 20, 0), // arrows\r\n                  d: 0\r\n                }, \r\n              },\r\n              sourceAnchor:3,\r\n              targetAnchor:3\r\n            }\r\n            graph.addItem(\"edge\", model);\r\n          }else if(target.id === \"delcondition\"){\r\n            \r\n          }\r\n        },\r\n        // offsetX and offsetY include the padding of the parent container\r\n        offsetX: 16 + 10,\r\n        offsetY: 0,\r\n        // the types of items that allow the menu show up\r\n        itemTypes: ['node'],\r\n      });\r\n\r\n      const edgeMenu = new G6.Menu({\r\n        getContent(evt) {\r\n          let header;\r\n          if (evt.target && evt.target.isCanvas && evt.target.isCanvas()) {\r\n            header = 'Canvas ContextMenu';\r\n          } else if (evt.item) {\r\n            const itemType = evt.item.getType();\r\n            header = `${itemType.toUpperCase()} Operation`;\r\n          }\r\n          return `\r\n          <h3>${header}</h3>\r\n          <ul>\r\n            <li id=\"delete\">Delete</li>\r\n            <li id=\"edit\">Edit</li>\r\n          </ul>`;\r\n        },\r\n        handleMenuClick: (target, item) => {\r\n          if(target.id === \"delete\"){\r\n            graph.removeItem(item);\r\n          }else if(target.id === \"edit\"){\r\n            let p = prompt(\"Please Edit STEP\", item.getModel().label);\r\n            const model = {\r\n              id: item.getID(),\r\n              label: p,\r\n            };\r\n            graph.updateItem(item, model);\r\n          }\r\n        },\r\n        // offsetX and offsetY include the padding of the parent container\r\n        offsetX: 16 + 10,\r\n        offsetY: 0,\r\n        // the types of items that allow the menu show up\r\n        itemTypes: ['edge'],\r\n      });\r\n\r\n\r\n      const graph = new G6.Graph({\r\n        container: 'mountNode',\r\n        width: 800, // graph width\r\n        height: 750, // graph height\r\n        modes: {\r\n          default: ['drag-canvas', 'zoom-canvas', 'drag-node'], // allow to drag\r\n        },\r\n        // fitView: true,\r\n        // fitViewPadding: [20, 40, 50, 20],\r\n        layout: {\r\n          \r\n          type: 'dagre',    \r\n          ranksep: 30,\r\n        },\r\n        // layout: {\r\n          \r\n        //   type: 'force',    \r\n        // },\r\n        plugins: [contextMenu, edgeMenu],\r\n        defaultNode: {\r\n          size: [450, 80], \r\n          style: {\r\n            fill: 'steelblue',\r\n            stroke: '#666',\r\n            lineWidth: 1, \r\n          },\r\n          anchorPoints:[[0.5,0],[0.5,1],[0,0.5],[1,0.5]],\r\n          \r\n          labelCfg: {\r\n            \r\n            style: {\r\n              fill: '#fff', // node text color\r\n              fontSize: 15, // node text size\r\n            },\r\n          },\r\n        },\r\n        defaultEdge: {\r\n          style: {\r\n            opacity: 0.6,\r\n            stroke: 'grey',\r\n            endArrow: {\r\n              path: G6.Arrow.vee(15, 20, 15), // arrows\r\n              d: 15\r\n            },        \r\n          },\r\n          // edg text\r\n          labelCfg: {\r\n            // autoRotate: true, \r\n            style:{\r\n              fontSize: 15,\r\n            }\r\n          },\r\n        },\r\n        nodeStateStyles: {\r\n          // hover\r\n          hover: {\r\n            fill: 'lightsteelblue',\r\n          },\r\n          // click\r\n          click: {\r\n            stroke: '#000',\r\n            lineWidth: 3,\r\n          },\r\n        },\r\n      });\r\n\r\n      function promptConfirm(){\r\n        let prompt = document.getElementById(\"prompt-text\").value;\r\n        if (prompt == \"\") {\r\n          alert(\"Please Enter Task.\")\r\n          return\r\n        }\r\n        let data = JSON.stringify({\"task_prompt\": prompt});\r\n        axios.post(\"http://127.0.0.1:8888/api/get_workflow\", data, {\r\n          headers: {\"Content-Type\": \"application/json\"}\r\n        })\r\n        .then(response => {\r\n          main(response.data);\r\n        })\r\n        .catch(error => {\r\n          alert(\"Network error, please try again.\")\r\n          console.error(error);\r\n        });\r\n      }\r\n\r\n      function switchLoading(bool){\r\n        let loadingEle = document.getElementById(\"mountNodeLoading\");\r\n        if(bool){\r\n          loadingEle.style.display = \"block\"\r\n        }else{\r\n          loadingEle.style.display = \"none\"\r\n        }\r\n      }\r\n      \r\n      function diaConfirm(){\r\n        let task_prompt = document.getElementById(\"prompt-text\").value;\r\n        let curr_workflow = G6ToData();\r\n        \r\n        let dialogues = document.getElementById(\"dialogues\");\r\n        let history = [];\r\n        for (let i = 0; i < dialogues.children.length; i++) {\r\n          let currentClass = dialogues.children[i].classList[0];\r\n          let currentText = dialogues.children[i].textContent;\r\n          let currentUser = \"\"\r\n          if (currentClass === \"dia-me\") {\r\n            currentUser = \"user\";\r\n          } else if (currentClass === \"dia-ai\") {\r\n            currentUser = \"assistant\";\r\n          }\r\n          history.push({\"role\": currentUser, \"content\":currentText});\r\n        }\r\n        let message = document.getElementById(\"message-text\").value;\r\n        document.getElementById(\"message-text\").value = \"\";\r\n        const messageDiv = document.createElement(\"div\");\r\n        messageDiv.className = \"dia-me\"\r\n        messageDiv.innerHTML = message;\r\n        dialogues.appendChild(messageDiv);\r\n\r\n        // post\r\n        let llm_res = \"\"\r\n        let data = JSON.stringify({\r\n          \"task_prompt\": task_prompt,\r\n          \"confirmed_workflow\": curr_workflow,\r\n          \"curr_input\": message,\r\n          \"history\": history\r\n        });\r\n        axios.post(\"http://127.0.0.1:8888/api/execute\", data, {\r\n          headers: {\"Content-Type\": \"application/json\"}\r\n        })\r\n        .then(response => {\r\n          llm_res = response.data;\r\n          const aiDiv = document.createElement(\"div\");\r\n          aiDiv.className = \"dia-ai\"\r\n          aiDiv.innerHTML = llm_res\r\n          dialogues.appendChild(aiDiv);\r\n        })\r\n        .catch(error => {\r\n          console.error(error);\r\n        });\r\n      }\r\n      const main = async (data) => {\r\n        update()\r\n        graph.data(dataToG6(data, -1));\r\n        graph.render();\r\n        graph.on('node:click', (e) => {\r\n          // set all clicked node to not clicked\r\n          const clickNodes = graph.findAllByState('node', 'click');\r\n          clickNodes.forEach((cn) => {\r\n            graph.setItemState(cn, 'click', false);\r\n          });\r\n          const nodeItem = e.item; // get the clicked node\r\n          graph.setItemState(nodeItem, 'click', true); // set the click status of current as true\r\n        });\r\n        graph.on('edge:click', (e) => {\r\n          console.log(e)\r\n          // set all clicked node to not clicked\r\n          const clickEdges = graph.findAllByState('edge', 'click');\r\n          clickEdges.forEach((cn) => {\r\n            graph.setItemState(cn, 'click', false);\r\n          });\r\n          const nodeItem = e.item; // get the clicked node\r\n          graph.setItemState(nodeItem, 'click', true); // set the click status of current as true\r\n        });\r\n      };\r\n      \r\n\r\n    </script>\r\n  </body>\r\n</html>"
  },
  {
    "path": "LowCodeLLM/src/lowCodeLLM.py",
    "content": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nfrom planningLLM import planningLLM\r\nfrom executingLLM import executingLLM\r\nimport json\r\n\r\nclass lowCodeLLM:\r\n    def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):\r\n        self.PLLM = planningLLM(PLLM_temperature)\r\n        self.ELLM = executingLLM(ELLM_temperature)\r\n\r\n    def get_workflow(self, task_prompt):\r\n        return self.PLLM.get_workflow(task_prompt)\r\n\r\n    def extend_workflow(self, task_prompt, current_workflow, step=''):\r\n        ''' generate a sub-workflow for one of steps \r\n            - input: the current workflow, the step needs to extend\r\n            - output: sub-workflow '''\r\n        workflow = self._json2txt(current_workflow)\r\n        return self.PLLM.extend_workflow(task_prompt, workflow, step)\r\n\r\n    def execute(self, task_prompt,confirmed_workflow, history, curr_input):\r\n        ''' chat with the workflow-equipped low-code LLM '''\r\n        prompt = [{'role': 'system', \"content\": 'The overall task you are facing is: '+task_prompt+\r\n                '\\nThe standard operating procedure(SOP) is:\\n'+self._json2txt(confirmed_workflow)}]\r\n        history = prompt + history\r\n        response = self.ELLM.execute(curr_input, history)\r\n        return response\r\n    \r\n    def _json2txt(self, workflow_json):\r\n        ''' convert the json workflow to text'''\r\n        def json2text_step(step):\r\n            step_res = \"\"\r\n            step_res += step[\"stepId\"] + \": [\" + step[\"stepName\"] + \"]\"\r\n            step_res += \"[\" + step[\"stepDescription\"] + \"][\"\r\n            for jump in step[\"jumpLogic\"]:\r\n                step_res += \"[[\" + jump[\"Condition\"] + \"][\" + jump[\"Target\"] + \"]],\"\r\n            step_res += \"]\\n\"\r\n            return step_res\r\n\r\n        workflow_txt = \"\"\r\n        for step in json.loads(workflow_json):\r\n            workflow_txt += json2text_step(step)\r\n            for substep in step['extension']:\r\n                workflow_txt += json2text_step(substep)\r\n        return workflow_txt"
  },
  {
    "path": "LowCodeLLM/src/openAIWrapper.py",
    "content": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport os\r\nimport openai\r\n\r\nclass OpenAIWrapper:\r\n    def __init__(self, temperature):\r\n        self.key = os.environ.get(\"OPENAIKEY\")\r\n        openai.api_key = self.key\r\n\r\n        # Access the USE_AZURE environment variable\r\n        self.use_azure = os.environ.get('USE_AZURE')\r\n\r\n        # Check if USE_AZURE is defined\r\n        if self.use_azure is not None:\r\n            # Convert the USE_AZURE value to boolean\r\n            self.use_azure = self.use_azure.lower() == 'true'\r\n        else:\r\n            self.use_azure = False\r\n\r\n        if self.use_azure:\r\n            openai.api_type = \"azure\"\r\n            self.api_base = os.environ.get('API_BASE')\r\n            openai.api_base = self.api_base\r\n            self.api_version = os.environ.get('API_VERSION')\r\n            openai.api_version = self.api_version\r\n            self.engine = os.environ.get('MODEL')\r\n        else:\r\n            self.chat_model_id = \"gpt-3.5-turbo\"\r\n            \r\n        self.temperature = temperature\r\n        self.max_tokens = 2048\r\n        self.top_p = 1\r\n        self.time_out = 7\r\n    \r\n    def run(self, prompt):\r\n        return self._post_request_chat(prompt)\r\n\r\n    def _post_request_chat(self, messages):\r\n        try:\r\n            if self.use_azure:\r\n                response = openai.ChatCompletion.create(\r\n                    engine=self.engine,\r\n                    messages=messages,\r\n                    temperature=self.temperature,\r\n                    max_tokens=self.max_tokens,\r\n                    frequency_penalty=0,\r\n                    presence_penalty=0\r\n                )\r\n            else:\r\n                response = openai.ChatCompletion.create(\r\n                    model=self.chat_model_id,\r\n                    messages=messages,\r\n                    temperature=self.temperature,\r\n                    max_tokens=self.max_tokens,\r\n                    frequency_penalty=0,\r\n                    presence_penalty=0\r\n                )\r\n            res = response['choices'][0]['message']['content']\r\n            return res, True\r\n        except Exception as e:\r\n            return \"\", False\r\n"
  },
  {
    "path": "LowCodeLLM/src/planningLLM.py",
    "content": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport re\r\nimport json\r\nfrom openAIWrapper import OpenAIWrapper\r\n\r\nPLANNING_LLM_PREFIX = \"\"\"Planning LLM is designed to provide a standard operating procedure so that an difficult task will be broken down into several steps, and the task will be easily solved by following these steps.\r\nPlanning LLM is a powerful problem-solving assistant, and it only needs to analyze the task and provide standard operating procedure as guidance, but does not need actually to solve the problem.\r\nSometimes there exists some unknown or undetermined situation, thus judgmental logic is needed: some \"conditions\" are listed, and the next step that should be carried out if a \"condition\" is satisfied is also listed. The judgmental logics are not necessary.\r\nPlanning LLM MUST only provide standard operating procedure in the following format without any other words:\r\n'''\r\nSTEP 1: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\r\nSTEP 2: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\r\n...\r\n'''\r\n\r\nFor example:\r\n'''\r\nSTEP 1: [Brainstorming][Choose a topic or prompt, and generate ideas and organize them into an outline][]\r\nSTEP 2: [Research][Gather information, take notes and organize them into the outline][[[lack of ideas][Jump to STEP 1]]]\r\n...\r\n'''\r\n\"\"\"\r\n\r\nEXTEND_PREFIX = \"\"\"\r\n\\nsome steps of the SOP provided by Planning LLM are too rough, so Planning LLM can also provide a detailed sub-SOP for the given step.\r\nRemember, Planning LLM take the overall SOP into consideration, and the sub-SOP MUST be consistent with the rest of the steps, and there MUST be no duplication in content between the extension and the original SOP.\r\n\r\nFor example:\r\nIf the overall SOP is:\r\n'''\r\nSTEP 1: [Brainstorming][Choose a topic or prompt, and generate ideas and organize them into an outline][]\r\nSTEP 2: [Write][write the text][]\r\n'''\r\nIf the STEP 2: \"write the text\" is too rough and needs to be extended, then the response could be:\r\n'''\r\nSTEP 2.1: [Write the title][write the title of the essay][]\r\nSTEP 2.2: [Write the body][write the body of the essay][[[if lack of materials][Jump to STEP 1]]]\r\n'''\r\n\"\"\"\r\n\r\nPLANNING_LLM_SUFFIX = \"\"\"\\nRemember: Planning LLM is very strict to the format and NEVER reply any word other than the standard operating procedure.\r\n\"\"\"\r\n\r\nclass planningLLM:\r\n    def __init__(self, temperature) -> None:\r\n        self.prefix = PLANNING_LLM_PREFIX\r\n        self.suffix = PLANNING_LLM_SUFFIX\r\n        self.LLM = OpenAIWrapper(temperature)\r\n        self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}]\r\n\r\n    def get_workflow(self, task_prompt):\r\n        '''\r\n        - input: task_prompt\r\n        - output: workflow (json)\r\n        '''\r\n        messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\r\n        response, status = self.LLM.run(messages)\r\n        if status:\r\n            return self._txt2json(response)\r\n        else:\r\n            return \"OpenAI API error.\"\r\n\r\n    def extend_workflow(self, task_prompt, current_workflow, step):\r\n        messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\r\n        messages.append({'role': 'user', \"content\": EXTEND_PREFIX+\r\n                         'The current SOP is:\\n'+current_workflow+\r\n                         '\\nThe step needs to be extended is:\\n'+step+\r\n                         PLANNING_LLM_SUFFIX})\r\n        response, status = self.LLM.run(messages)\r\n        if status:\r\n            return self._txt2json(response)\r\n        else:\r\n            return \"OpenAI API error.\"\r\n\r\n    def _txt2json(self, workflow_txt):\r\n        ''' convert the workflow in natural language to json format '''\r\n        workflow = []\r\n        try:\r\n            steps = workflow_txt.split('\\n')\r\n            for step in steps:\r\n                if step[0:4] != \"STEP\":\r\n                    continue\r\n                left_indices = [_.start() for _ in re.finditer(\"\\[\", step)]\r\n                right_indices = [_.start() for _ in re.finditer(\"\\]\", step)]\r\n                step_id = step[: left_indices[0]-2]\r\n                step_name = step[left_indices[0]+1: right_indices[0]]\r\n                step_description = step[left_indices[1]+1: right_indices[1]]\r\n                jump_str = step[left_indices[2]+1: right_indices[-1]]\r\n                if re.findall(re.compile(r'[A-Za-z]',re.S), jump_str) == []:\r\n                    workflow.append({\"stepId\": step_id, \"stepName\": step_name, \"stepDescription\": step_description, \"jumpLogic\": [], \"extension\": []})\r\n                    continue\r\n                jump_logic = []\r\n                left_indices = [_.start() for _ in re.finditer('\\[', jump_str)]\r\n                right_indices = [_.start() for _ in re.finditer('\\]', jump_str)]\r\n                i = 1\r\n                while i < len(left_indices):\r\n                    jump = {\"Condition\": jump_str[left_indices[i]+1: right_indices[i-1]], \"Target\": re.search(r'STEP\\s\\d', jump_str[left_indices[i+1]+1: right_indices[i]]).group(0)}\r\n                    jump_logic.append(jump)\r\n                    i += 3\r\n                workflow.append({\"stepId\": step_id, \"stepName\": step_name, \"stepDescription\": step_description, \"jumpLogic\": jump_logic, \"extension\": []})\r\n            return json.dumps(workflow)\r\n        except:\r\n            print(\"Format error, please try again.\")"
  },
  {
    "path": "LowCodeLLM/src/requirements.txt",
    "content": "Flask==2.2.5\r\nFlask_Cors==3.0.10\r\nopenai==0.27.2\r\ngunicorn==20.1.0\r\ngevent==21.8.0\r\n"
  },
  {
    "path": "LowCodeLLM/src/supervisord.conf",
    "content": "[supervisord]\r\nnodaemon=true\r\nloglevel=info\r\n\r\n[program:flask]\r\ncommand=gunicorn --timeout 300 --bind \"0.0.0.0:8888\" \"app:app\" --log-level debug --capture-output --worker-class gevent\r\npriority=999\r\nstdout_logfile=/dev/stdout\r\nstdout_logfile_maxbytes=0\r\nstderr_logfile=/dev/stdout\r\nstderr_logfile_maxbytes=0\r\nautorestart=true"
  },
  {
    "path": "LowCodeLLM/src/test/test_execute.py",
    "content": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport json\r\nimport sys\r\nimport os\r\nimport time\r\nsys.path.append(os.getcwd())\r\n\r\ndef test_extend_workflow():\r\n    from lowCodeLLM import lowCodeLLM\r\n    cases = json.load(open(\"./test/testcases/execute_test_cases.json\", \"r\"))\r\n    llm = lowCodeLLM(0.5, 0)\r\n    for c in cases:\r\n        task_prompt = c[\"task_prompt\"]\r\n        confirmed_workflow = c[\"confirmed_workflow\"]\r\n        history = c[\"history\"]\r\n        curr_input = c[\"curr_input\"]\r\n        result = llm.execute(task_prompt, confirmed_workflow, history, curr_input)\r\n        time.sleep(5)\r\n        assert type(result) == str\r\n        assert len(result) > 0"
  },
  {
    "path": "LowCodeLLM/src/test/test_extend_workflow.py",
    "content": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport json\r\nimport sys\r\nimport os\r\nimport time\r\nsys.path.append(os.getcwd())\r\n\r\ndef test_extend_workflow():\r\n    from lowCodeLLM import lowCodeLLM\r\n    cases = json.load(open(\"./test/testcases/extend_workflow_test_cases.json\", \"r\"))\r\n    llm = lowCodeLLM(0.5, 0)\r\n    for c in cases:\r\n        task_prompt = c[\"task_prompt\"]\r\n        current_workflow = c[\"current_workflow\"]\r\n        step = c[\"step\"]\r\n        result = llm.extend_workflow(task_prompt, current_workflow, step)\r\n        time.sleep(5)\r\n        assert len(json.loads(result)) >= 1"
  },
  {
    "path": "LowCodeLLM/src/test/test_get_workflow.py",
    "content": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport json\r\nimport sys\r\nimport os\r\nsys.path.append(os.getcwd())\r\n\r\ndef test_get_workflow():\r\n    from lowCodeLLM import lowCodeLLM\r\n    cases = json.load(open(\"./test/testcases/get_workflow_test_cases.json\", \"r\"))\r\n    llm = lowCodeLLM(0.5, 0)\r\n    for c in cases:\r\n        task_prompt = c[\"task_prompt\"]\r\n        result = llm.get_workflow(task_prompt)\r\n        assert len(json.loads(result)) >= 1"
  },
  {
    "path": "LowCodeLLM/src/test/testcases/execute_test_cases.json",
    "content": "[\r\n    {\r\n        \"task_prompt\": \"Write an essay about drunk driving issue.\",\r\n        \"confirmed_workflow\": \"[{\\\"stepId\\\": \\\"STEP 1\\\", \\\"stepName\\\": \\\"Research\\\", \\\"stepDescription\\\": \\\"Gather statistics and information about drunk driving issue\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 2\\\", \\\"stepName\\\": \\\"Identify the causes\\\", \\\"stepDescription\\\": \\\"Analyze the reasons behind drunk driving\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 3\\\", \\\"stepName\\\": \\\"Examine the consequences\\\", \\\"stepDescription\\\": \\\"Investigate the outcomes of drunk driving\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 4\\\", \\\"stepName\\\": \\\"Develop a prevention plan\\\", \\\"stepDescription\\\": \\\"Create a plan to prevent drunk driving\\\", \\\"jumpLogic\\\": [{\\\"Condition\\\": \\\"if 'lack of information'\\\", \\\"Target\\\": \\\"STEP 1\\\"}, {\\\"Condition\\\": \\\"if 'unclear causes'\\\", \\\"Target\\\": \\\"STEP 2\\\"}, {\\\"Condition\\\": \\\"if 'incomplete analysis'\\\", \\\"Target\\\": \\\"STEP 2\\\"}, {\\\"Condition\\\": \\\"if 'unrealistic plan'\\\", \\\"Target\\\": \\\"STEP 4\\\"}], \\\"extension\\\": []}]\",\r\n        \"history\": [],\r\n        \"curr_input\": \"write the essay and show me.\"\r\n    },\r\n    {\r\n        \"task_prompt\": \"Write an bolg about Microsoft.\",\r\n        \"confirmed_workflow\": \"[{\\\"stepId\\\": \\\"STEP 1\\\", \\\"stepName\\\": \\\"Research\\\", \\\"stepDescription\\\": \\\"Gather information about Microsoft's history, products, and services\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 2\\\", \\\"stepName\\\": \\\"Analyze\\\", \\\"stepDescription\\\": \\\"Organize the gathered information into categories and identify key points\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 3\\\", \\\"stepName\\\": \\\"Outline\\\", \\\"stepDescription\\\": \\\"Create an outline based on the key points and categories\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 4\\\", \\\"stepName\\\": \\\"Write\\\", \\\"stepDescription\\\": \\\"Write a draft of the blog post using the outline as a guide\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 5\\\", \\\"stepName\\\": \\\"Edit\\\", \\\"stepDescription\\\": \\\"Review and revise the draft for clarity and accuracy\\\", \\\"jumpLogic\\\": [{\\\"Condition\\\": \\\"need for further editing\\\", \\\"Target\\\": \\\"STEP 4\\\"}], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 6\\\", \\\"stepName\\\": \\\"Publish\\\", \\\"stepDescription\\\": \\\"Post the final version of the blog post on a suitable platform\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}]\",\r\n        \"history\": [],\r\n        \"curr_input\": \"write the blog and show me.\"\r\n    },\r\n    {\r\n        \"task_prompt\": \"I want to write a two-player battle game.\",\r\n        \"confirmed_workflow\": \"[{\\\"stepId\\\": \\\"STEP 1\\\", \\\"stepName\\\": \\\"Game Concept\\\", \\\"stepDescription\\\": \\\"Decide on the game concept and mechanics\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 2\\\", \\\"stepName\\\": \\\"Game Design\\\", \\\"stepDescription\\\": \\\"Create a rough sketch of the game, including the game board, characters, and rules\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 3\\\", \\\"stepName\\\": \\\"Programming\\\", \\\"stepDescription\\\": \\\"Write the code for the game\\\", \\\"jumpLogic\\\": [{\\\"Condition\\\": \\\"if 'game mechanics are too complex'\\\", \\\"Target\\\": \\\"STEP 1\\\"}], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 4\\\", \\\"stepName\\\": \\\"Testing\\\", \\\"stepDescription\\\": \\\"Test the game for bugs and glitches\\\", \\\"jumpLogic\\\": [{\\\"Condition\\\": \\\"if 'gameplay is not balanced'\\\", \\\"Target\\\": \\\"STEP 2\\\"}], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 5\\\", \\\"stepName\\\": \\\"Polishing\\\", \\\"stepDescription\\\": \\\"Add finishing touches to the game, including graphics and sound effects\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 6\\\", \\\"stepName\\\": \\\"Release\\\", \\\"stepDescription\\\": \\\"Publish the game for players to enjoy\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}]\",\r\n        \"history\": [{\"role\": \"asistant\", \"content\": \"sure, I can write it for you, do you want me show you the code?\"}],\r\n        \"curr_input\": \"Sure.\"\r\n    }\r\n]"
  },
  {
    "path": "LowCodeLLM/src/test/testcases/extend_workflow_test_cases.json",
    "content": "[\r\n    {\r\n        \"task_prompt\": \"Write an essay about drunk driving issue.\",\r\n        \"current_workflow\": \"[{\\\"stepId\\\": \\\"STEP 1\\\", \\\"stepName\\\": \\\"Research\\\", \\\"stepDescription\\\": \\\"Gather statistics and information about drunk driving issue\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 2\\\", \\\"stepName\\\": \\\"Identify the causes\\\", \\\"stepDescription\\\": \\\"Analyze the reasons behind drunk driving\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 3\\\", \\\"stepName\\\": \\\"Examine the consequences\\\", \\\"stepDescription\\\": \\\"Investigate the outcomes of drunk driving\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 4\\\", \\\"stepName\\\": \\\"Develop a prevention plan\\\", \\\"stepDescription\\\": \\\"Create a plan to prevent drunk driving\\\", \\\"jumpLogic\\\": [{\\\"Condition\\\": \\\"if 'lack of information'\\\", \\\"Target\\\": \\\"STEP 1\\\"}, {\\\"Condition\\\": \\\"if 'unclear causes'\\\", \\\"Target\\\": \\\"STEP 2\\\"}, {\\\"Condition\\\": \\\"if 'incomplete analysis'\\\", \\\"Target\\\": \\\"STEP 2\\\"}, {\\\"Condition\\\": \\\"if 'unrealistic plan'\\\", \\\"Target\\\": \\\"STEP 4\\\"}], \\\"extension\\\": []}]\",\r\n        \"step\": \"STEP 1\"\r\n    },\r\n    {\r\n        \"task_prompt\": \"Write an bolg about Microsoft.\",\r\n        \"current_workflow\": \"[{\\\"stepId\\\": \\\"STEP 1\\\", \\\"stepName\\\": \\\"Research\\\", \\\"stepDescription\\\": \\\"Gather information about Microsoft's history, products, and services\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 2\\\", \\\"stepName\\\": \\\"Analyze\\\", \\\"stepDescription\\\": \\\"Organize the gathered information into categories and identify key points\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 3\\\", \\\"stepName\\\": \\\"Outline\\\", \\\"stepDescription\\\": \\\"Create an outline based on the key points and categories\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 4\\\", \\\"stepName\\\": \\\"Write\\\", \\\"stepDescription\\\": \\\"Write a draft of the blog post using the outline as a guide\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 5\\\", \\\"stepName\\\": \\\"Edit\\\", \\\"stepDescription\\\": \\\"Review and revise the draft for clarity and accuracy\\\", \\\"jumpLogic\\\": [{\\\"Condition\\\": \\\"need for further editing\\\", \\\"Target\\\": \\\"STEP 4\\\"}], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 6\\\", \\\"stepName\\\": \\\"Publish\\\", \\\"stepDescription\\\": \\\"Post the final version of the blog post on a suitable platform\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}]\",\r\n        \"step\": \"STEP 2\"\r\n    },\r\n    {\r\n        \"task_prompt\": \"I want to write a two-player battle game.\",\r\n        \"current_workflow\": \"[{\\\"stepId\\\": \\\"STEP 1\\\", \\\"stepName\\\": \\\"Game Concept\\\", \\\"stepDescription\\\": \\\"Decide on the game concept and mechanics\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 2\\\", \\\"stepName\\\": \\\"Game Design\\\", \\\"stepDescription\\\": \\\"Create a rough sketch of the game, including the game board, characters, and rules\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 3\\\", \\\"stepName\\\": \\\"Programming\\\", \\\"stepDescription\\\": \\\"Write the code for the game\\\", \\\"jumpLogic\\\": [{\\\"Condition\\\": \\\"if 'game mechanics are too complex'\\\", \\\"Target\\\": \\\"STEP 1\\\"}], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 4\\\", \\\"stepName\\\": \\\"Testing\\\", \\\"stepDescription\\\": \\\"Test the game for bugs and glitches\\\", \\\"jumpLogic\\\": [{\\\"Condition\\\": \\\"if 'gameplay is not balanced'\\\", \\\"Target\\\": \\\"STEP 2\\\"}], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 5\\\", \\\"stepName\\\": \\\"Polishing\\\", \\\"stepDescription\\\": \\\"Add finishing touches to the game, including graphics and sound effects\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}, {\\\"stepId\\\": \\\"STEP 6\\\", \\\"stepName\\\": \\\"Release\\\", \\\"stepDescription\\\": \\\"Publish the game for players to enjoy\\\", \\\"jumpLogic\\\": [], \\\"extension\\\": []}]\",\r\n        \"step\": \"STEP 3\"\r\n    }\r\n]"
  },
  {
    "path": "LowCodeLLM/src/test/testcases/get_workflow_test_cases.json",
    "content": "[\r\n    {\r\n        \"task_prompt\": \"Write an essay about drunk driving issue.\"\r\n    },\r\n    {\r\n        \"task_prompt\": \"Write an bolg about Microsoft.\"\r\n    },\r\n    {\r\n        \"task_prompt\": \"I want to write a two-player battle game.\"\r\n    }\r\n]"
  },
  {
    "path": "README.md",
    "content": "# TaskMatrix\n\n**TaskMatrix** connects ChatGPT and a series of Visual Foundation Models to enable **sending** and **receiving** images during chatting.\n\nSee our paper: [<font size=5>Visual ChatGPT: Talking, Drawing and Editing with Visual Foundation Models</font>](https://arxiv.org/abs/2303.04671)\n\n<a src=\"https://img.shields.io/badge/%F0%9F%A4%97-Open%20in%20Spaces-blue\" href=\"https://huggingface.co/spaces/microsoft/visual_chatgpt\">\n    <img src=\"https://img.shields.io/badge/%F0%9F%A4%97-Open%20in%20Spaces-blue\" alt=\"Open in Spaces\">\n</a>\n\n<a src=\"https://colab.research.google.com/assets/colab-badge.svg\" href=\"https://colab.research.google.com/drive/1P3jJqKEWEaeNcZg8fODbbWeQ3gxOHk2-?usp=sharing\">\n    <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open in Colab\">\n</a>\n\n## Updates:\n- Now TaskMatrix supports [GroundingDINO](https://github.com/IDEA-Research/GroundingDINO) and [segment-anything](https://github.com/facebookresearch/segment-anything)! Thanks **@jordddan** for his efforts. For the image editing case, `GroundingDINO` is first used to locate bounding boxes guided by given text, then `segment-anything` is used to generate the related mask, and finally stable diffusion inpainting is used to edit image based on the mask. \n    - Firstly, run `python visual_chatgpt.py --load \"Text2Box_cuda:0,Segmenting_cuda:0,Inpainting_cuda:0,ImageCaptioning_cuda:0\"`\n    - Then, say `find xxx in the image` or `segment xxx in the image`. `xxx` is an object. TaskMatrix will return the detection or segmentation result!\n\n\n- Now TaskMatrix can support Chinese! Thanks to **@Wang-Xiaodong1899** for his efforts.\n- We propose the **template** idea in TaskMatrix!\n    - A template is a **pre-defined execution flow** that assists ChatGPT in assembling complex tasks involving multiple foundation models. \n    - A template contains the **experiential solution** to complex tasks as determined by humans. \n    - A template can **invoke multiple foundation models** or even **establish a new ChatGPT session**\n    - To define a **template**, simply adding a class with attributes `template_model = True`\n- Thanks to **@ShengmingYin** and **@thebestannie** for providing a template example in `InfinityOutPainting` class (see the following gif)\n    - Firstly, run `python visual_chatgpt.py --load \"Inpainting_cuda:0,ImageCaptioning_cuda:0,VisualQuestionAnswering_cuda:0\"`\n    - Secondly, say `extend the image to 2048x1024` to TaskMatrix!\n    - By simply creating an `InfinityOutPainting` template, TaskMatrix can seamlessly extend images to any size through collaboration with existing `ImageCaptioning`, `Inpainting`, and `VisualQuestionAnswering` foundation models, **without the need for additional training**.\n- **TaskMatrix needs the effort of the community! We crave your contribution to add new and interesting features!**\n<img src=\"./assets/demo_inf.gif\" width=\"750\">\n\n\n## Insight & Goal:\nOn the one hand, **ChatGPT (or LLMs)** serves as a **general interface** that provides a broad and diverse understanding of a\nwide range of topics. On the other hand, **Foundation Models** serve as **domain experts** by providing deep knowledge in specific domains.\nBy leveraging **both general and deep knowledge**, we aim at building an AI that is capable of handling various tasks.\n\n\n## Demo \n<img src=\"./assets/demo_short.gif\" width=\"750\">\n\n##  System Architecture \n\n \n<p align=\"center\"><img src=\"./assets/figure.jpg\" alt=\"Logo\"></p>\n\n\n## Quick Start\n\n```\n# clone the repo\ngit clone https://github.com/microsoft/TaskMatrix.git\n\n# Go to directory\ncd visual-chatgpt\n\n# create a new environment\nconda create -n visgpt python=3.8\n\n# activate the new environment\nconda activate visgpt\n\n#  prepare the basic environments\npip install -r requirements.txt\npip install  git+https://github.com/IDEA-Research/GroundingDINO.git\npip install  git+https://github.com/facebookresearch/segment-anything.git\n\n# prepare your private OpenAI key (for Linux)\nexport OPENAI_API_KEY={Your_Private_Openai_Key}\n\n# prepare your private OpenAI key (for Windows)\nset OPENAI_API_KEY={Your_Private_Openai_Key}\n\n# Start TaskMatrix !\n# You can specify the GPU/CPU assignment by \"--load\", the parameter indicates which \n# Visual Foundation Model to use and where it will be loaded to\n# The model and device are separated by underline '_', the different models are separated by comma ','\n# The available Visual Foundation Models can be found in the following table\n# For example, if you want to load ImageCaptioning to cpu and Text2Image to cuda:0\n# You can use: \"ImageCaptioning_cpu,Text2Image_cuda:0\"\n\n# Advice for CPU Users\npython visual_chatgpt.py --load ImageCaptioning_cpu,Text2Image_cpu\n\n# Advice for 1 Tesla T4 15GB  (Google Colab)                       \npython visual_chatgpt.py --load \"ImageCaptioning_cuda:0,Text2Image_cuda:0\"\n                                \n# Advice for 4 Tesla V100 32GB                            \npython visual_chatgpt.py --load \"Text2Box_cuda:0,Segmenting_cuda:0,\n    Inpainting_cuda:0,ImageCaptioning_cuda:0,\n    Text2Image_cuda:1,Image2Canny_cpu,CannyText2Image_cuda:1,\n    Image2Depth_cpu,DepthText2Image_cuda:1,VisualQuestionAnswering_cuda:2,\n    InstructPix2Pix_cuda:2,Image2Scribble_cpu,ScribbleText2Image_cuda:2,\n    SegText2Image_cuda:2,Image2Pose_cpu,PoseText2Image_cuda:2,\n    Image2Hed_cpu,HedText2Image_cuda:3,Image2Normal_cpu,\n    NormalText2Image_cuda:3,Image2Line_cpu,LineText2Image_cuda:3\"\n\n```\n\n## GPU memory usage\nHere we list the GPU memory usage of each visual foundation model, you can specify which one you like:\n\n| Foundation Model        | GPU Memory (MB) |\n|------------------------|-----------------|\n| ImageEditing           | 3981            |\n| InstructPix2Pix        | 2827            |\n| Text2Image             | 3385            |\n| ImageCaptioning        | 1209            |\n| Image2Canny            | 0               |\n| CannyText2Image        | 3531            |\n| Image2Line             | 0               |\n| LineText2Image         | 3529            |\n| Image2Hed              | 0               |\n| HedText2Image          | 3529            |\n| Image2Scribble         | 0               |\n| ScribbleText2Image     | 3531            |\n| Image2Pose             | 0               |\n| PoseText2Image         | 3529            |\n| Image2Seg              | 919             |\n| SegText2Image          | 3529            |\n| Image2Depth            | 0               |\n| DepthText2Image        | 3531            |\n| Image2Normal           | 0               |\n| NormalText2Image       | 3529            |\n| VisualQuestionAnswering| 1495            |\n\n## Acknowledgement\nWe appreciate the open source of the following projects:\n\n[Hugging Face](https://github.com/huggingface) &#8194;\n[LangChain](https://github.com/hwchase17/langchain) &#8194;\n[Stable Diffusion](https://github.com/CompVis/stable-diffusion) &#8194; \n[ControlNet](https://github.com/lllyasviel/ControlNet) &#8194; \n[InstructPix2Pix](https://github.com/timothybrooks/instruct-pix2pix) &#8194; \n[CLIPSeg](https://github.com/timojl/clipseg) &#8194;\n[BLIP](https://github.com/salesforce/BLIP) &#8194;\n\n## Contact Information\nFor help or issues using the TaskMatrix, please submit a GitHub issue.\n\nFor other communications, please contact Chenfei WU (chewu@microsoft.com) or Nan DUAN (nanduan@microsoft.com).\n\n## Trademark Notice\n\nTrademarks This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft’s Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies.\n\n## Disclaimer\nThe recommended models in this Repo are just examples, used for scientific research exploring the concept of task automation and benchmarking with the paper published at [Visual ChatGPT: Talking, Drawing and Editing with Visual Foundation Models](https://arxiv.org/abs/2303.04671). Users can replace the models in this Repo according to their research needs. When using the recommended models in this Repo, you need to comply with the licenses of these models respectively. Microsoft shall not be held liable for any infringement of third-party rights resulting from your usage of this repo. Users agree to defend, indemnify and hold Microsoft harmless from and against all damages, costs, and attorneys' fees in connection with any claims arising from this Repo. If anyone believes that this Repo infringes on your rights, please notify the project owner [email](chewu@microsoft.com).\n"
  },
  {
    "path": "SECURITY.md",
    "content": "<!-- BEGIN MICROSOFT SECURITY.MD V0.0.7 BLOCK -->\n\n## Security\n\nMicrosoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).\n\nIf you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below.\n\n## Reporting Security Issues\n\n**Please do not report security vulnerabilities through public GitHub issues.**\n\nInstead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report).\n\nIf you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com).  If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey).\n\nYou should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). \n\nPlease include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:\n\n  * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)\n  * Full paths of source file(s) related to the manifestation of the issue\n  * The location of the affected source code (tag/branch/commit or direct URL)\n  * Any special configuration required to reproduce the issue\n  * Step-by-step instructions to reproduce the issue\n  * Proof-of-concept or exploit code (if possible)\n  * Impact of the issue, including how an attacker might exploit the issue\n\nThis information will help us triage your report more quickly.\n\nIf you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs.\n\n## Preferred Languages\n\nWe prefer all communications to be in English.\n\n## Policy\n\nMicrosoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd).\n\n<!-- END MICROSOFT SECURITY.MD BLOCK -->"
  },
  {
    "path": "TaskMatrix.AI/README.md",
    "content": "## Description\n**TaskMatrix.AI** is an AI ecosystem that can connect foundation models with millions of APIs for task completion. Unlike most previous work that aimed to improve a single AI model, TaskMatrix.AI focuses more on using existing foundation models (as a brain-like central system) and APIs of other AI models and systems (as sub-task solvers) to achieve diversified tasks in both digital and physical domains. Visual ChatGPT is just an example of applying TaskMatrix.AI to the visual domain.\n\n## Paper\n[TaskMatrix.AI](https://arxiv.org/abs/2303.16434)\n\n## Online System\nIn progress, coming in the near future...\n\n## Paradigm Shift\n<img src=\"https://github.com/microsoft/visual-chatgpt/blob/main/assets/paradigm.png\" width=\"1000\">\n\n## System Overview\n<img src=\"https://github.com/microsoft/visual-chatgpt/blob/main/assets/overview.png\" width=\"1000\">\n"
  },
  {
    "path": "requirements.txt",
    "content": "langchain==0.0.101\ntorch==1.13.1\ntorchvision==0.14.1\nwget==3.2\naccelerate\naddict\nalbumentations\nbasicsr\ncontrolnet-aux\ndiffusers\neinops\ngradio\nimageio\nimageio-ffmpeg\ninvisible-watermark\nkornia\nnumpy\nomegaconf\nopen_clip_torch\nopenai\nopencv-python\nprettytable\nsafetensors\nstreamlit\ntest-tube\ntimm\ntorchmetrics\ntransformers\nwebdataset\nyapf\n"
  },
  {
    "path": "visual_chatgpt.py",
    "content": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n# coding: utf-8\nimport os\nimport gradio as gr\nimport random\nimport torch\nimport cv2\nimport re\nimport uuid\nfrom PIL import Image, ImageDraw, ImageOps, ImageFont\nimport math\nimport numpy as np\nimport argparse\nimport inspect\nimport tempfile\nfrom transformers import CLIPSegProcessor, CLIPSegForImageSegmentation\nfrom transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering\nfrom transformers import AutoImageProcessor, UperNetForSemanticSegmentation\n\nfrom diffusers import StableDiffusionPipeline, StableDiffusionInpaintPipeline, StableDiffusionInstructPix2PixPipeline\nfrom diffusers import EulerAncestralDiscreteScheduler\nfrom diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler\nfrom diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker\n\nfrom controlnet_aux import OpenposeDetector, MLSDdetector, HEDdetector\n\nfrom langchain.agents.initialize import initialize_agent\nfrom langchain.agents.tools import Tool\nfrom langchain.chains.conversation.memory import ConversationBufferMemory\nfrom langchain.llms.openai import OpenAI\n\n# Grounding DINO\nimport groundingdino.datasets.transforms as T\nfrom groundingdino.models import build_model\nfrom groundingdino.util import box_ops\nfrom groundingdino.util.slconfig import SLConfig\nfrom groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap\n\n# segment anything\nfrom segment_anything import build_sam, SamPredictor, SamAutomaticMaskGenerator\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport wget\n\nVISUAL_CHATGPT_PREFIX = \"\"\"Visual ChatGPT is designed to be able to assist with a wide range of text and visual related tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. Visual ChatGPT is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nVisual ChatGPT is able to process and understand large amounts of text and images. As a language model, Visual ChatGPT can not directly read images, but it has a list of tools to finish different visual tasks. Each image will have a file name formed as \"image/xxx.png\", and Visual ChatGPT can invoke different tools to indirectly understand pictures. When talking about images, Visual ChatGPT is very strict to the file name and will never fabricate nonexistent files. When using tools to generate new image files, Visual ChatGPT is also known that the image may not be the same as the user's demand, and will use other visual question answering tools or description tools to observe the real image. Visual ChatGPT is able to use tools in a sequence, and is loyal to the tool observation outputs rather than faking the image content and image file name. It will remember to provide the file name from the last tool observation, if a new image is generated.\n\nHuman may provide new figures to Visual ChatGPT with a description. The description helps Visual ChatGPT to understand this image, but Visual ChatGPT should use tools to finish following tasks, rather than directly imagine from the description.\n\nOverall, Visual ChatGPT is a powerful visual dialogue assistant tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. \n\n\nTOOLS:\n------\n\nVisual ChatGPT  has access to the following tools:\"\"\"\n\nVISUAL_CHATGPT_FORMAT_INSTRUCTIONS = \"\"\"To use a tool, please use the following format:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\nWhen you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response here]\n```\n\"\"\"\n\nVISUAL_CHATGPT_SUFFIX = \"\"\"You are very strict to the filename correctness and will never fake a file name if it does not exist.\nYou will remember to provide the image file name loyally if it's provided in the last tool observation.\n\nBegin!\n\nPrevious conversation history:\n{chat_history}\n\nNew input: {input}\nSince Visual ChatGPT is a text language model, Visual ChatGPT must use tools to observe images rather than imagination.\nThe thoughts and observations are only visible for Visual ChatGPT, Visual ChatGPT should remember to repeat important information in the final response for Human. \nThought: Do I need to use a tool? {agent_scratchpad} Let's think step by step.\n\"\"\"\n\nVISUAL_CHATGPT_PREFIX_CN = \"\"\"Visual ChatGPT 旨在能够协助完成范围广泛的文本和视觉相关任务，从回答简单的问题到提供对广泛主题的深入解释和讨论。 Visual ChatGPT 能够根据收到的输入生成类似人类的文本，使其能够进行听起来自然的对话，并提供连贯且与手头主题相关的响应。\n\nVisual ChatGPT 能够处理和理解大量文本和图像。作为一种语言模型，Visual ChatGPT 不能直接读取图像，但它有一系列工具来完成不同的视觉任务。每张图片都会有一个文件名，格式为“image/xxx.png”，Visual ChatGPT可以调用不同的工具来间接理解图片。在谈论图片时，Visual ChatGPT 对文件名的要求非常严格，绝不会伪造不存在的文件。在使用工具生成新的图像文件时，Visual ChatGPT也知道图像可能与用户需求不一样，会使用其他视觉问答工具或描述工具来观察真实图像。 Visual ChatGPT 能够按顺序使用工具，并且忠于工具观察输出，而不是伪造图像内容和图像文件名。如果生成新图像，它将记得提供上次工具观察的文件名。\n\nHuman 可能会向 Visual ChatGPT 提供带有描述的新图形。描述帮助 Visual ChatGPT 理解这个图像，但 Visual ChatGPT 应该使用工具来完成以下任务，而不是直接从描述中想象。有些工具将会返回英文描述，但你对用户的聊天应当采用中文。\n\n总的来说，Visual ChatGPT 是一个强大的可视化对话辅助工具，可以帮助处理范围广泛的任务，并提供关于范围广泛的主题的有价值的见解和信息。\n\n工具列表:\n------\n\nVisual ChatGPT 可以使用这些工具:\"\"\"\n\nVISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN = \"\"\"用户使用中文和你进行聊天，但是工具的参数应当使用英文。如果要调用工具，你必须遵循如下格式:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\n当你不再需要继续调用工具，而是对观察结果进行总结回复时，你必须使用如下格式：\n\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response here]\n```\n\"\"\"\n\nVISUAL_CHATGPT_SUFFIX_CN = \"\"\"你对文件名的正确性非常严格，而且永远不会伪造不存在的文件。\n\n开始!\n\n因为Visual ChatGPT是一个文本语言模型，必须使用工具去观察图片而不是依靠想象。\n推理想法和观察结果只对Visual ChatGPT可见，需要记得在最终回复时把重要的信息重复给用户，你只能给用户返回中文句子。我们一步一步思考。在你使用工具时，工具的参数只能是英文。\n\n聊天历史:\n{chat_history}\n\n新输入: {input}\nThought: Do I need to use a tool? {agent_scratchpad}\n\"\"\"\n\nos.makedirs('image', exist_ok=True)\n\n\ndef seed_everything(seed):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n    return seed\n\n\ndef prompts(name, description):\n    def decorator(func):\n        func.name = name\n        func.description = description\n        return func\n\n    return decorator\n\n\ndef blend_gt2pt(old_image, new_image, sigma=0.15, steps=100):\n    new_size = new_image.size\n    old_size = old_image.size\n    easy_img = np.array(new_image)\n    gt_img_array = np.array(old_image)\n    pos_w = (new_size[0] - old_size[0]) // 2\n    pos_h = (new_size[1] - old_size[1]) // 2\n\n    kernel_h = cv2.getGaussianKernel(old_size[1], old_size[1] * sigma)\n    kernel_w = cv2.getGaussianKernel(old_size[0], old_size[0] * sigma)\n    kernel = np.multiply(kernel_h, np.transpose(kernel_w))\n\n    kernel[steps:-steps, steps:-steps] = 1\n    kernel[:steps, :steps] = kernel[:steps, :steps] / kernel[steps - 1, steps - 1]\n    kernel[:steps, -steps:] = kernel[:steps, -steps:] / kernel[steps - 1, -(steps)]\n    kernel[-steps:, :steps] = kernel[-steps:, :steps] / kernel[-steps, steps - 1]\n    kernel[-steps:, -steps:] = kernel[-steps:, -steps:] / kernel[-steps, -steps]\n    kernel = np.expand_dims(kernel, 2)\n    kernel = np.repeat(kernel, 3, 2)\n\n    weight = np.linspace(0, 1, steps)\n    top = np.expand_dims(weight, 1)\n    top = np.repeat(top, old_size[0] - 2 * steps, 1)\n    top = np.expand_dims(top, 2)\n    top = np.repeat(top, 3, 2)\n\n    weight = np.linspace(1, 0, steps)\n    down = np.expand_dims(weight, 1)\n    down = np.repeat(down, old_size[0] - 2 * steps, 1)\n    down = np.expand_dims(down, 2)\n    down = np.repeat(down, 3, 2)\n\n    weight = np.linspace(0, 1, steps)\n    left = np.expand_dims(weight, 0)\n    left = np.repeat(left, old_size[1] - 2 * steps, 0)\n    left = np.expand_dims(left, 2)\n    left = np.repeat(left, 3, 2)\n\n    weight = np.linspace(1, 0, steps)\n    right = np.expand_dims(weight, 0)\n    right = np.repeat(right, old_size[1] - 2 * steps, 0)\n    right = np.expand_dims(right, 2)\n    right = np.repeat(right, 3, 2)\n\n    kernel[:steps, steps:-steps] = top\n    kernel[-steps:, steps:-steps] = down\n    kernel[steps:-steps, :steps] = left\n    kernel[steps:-steps, -steps:] = right\n\n    pt_gt_img = easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]]\n    gaussian_gt_img = kernel * gt_img_array + (1 - kernel) * pt_gt_img  # gt img with blur img\n    gaussian_gt_img = gaussian_gt_img.astype(np.int64)\n    easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]] = gaussian_gt_img\n    gaussian_img = Image.fromarray(easy_img)\n    return gaussian_img\n\n\ndef cut_dialogue_history(history_memory, keep_last_n_words=500):\n    if history_memory is None or len(history_memory) == 0:\n        return history_memory\n    tokens = history_memory.split()\n    n_tokens = len(tokens)\n    print(f\"history_memory:{history_memory}, n_tokens: {n_tokens}\")\n    if n_tokens < keep_last_n_words:\n        return history_memory\n    paragraphs = history_memory.split('\\n')\n    last_n_tokens = n_tokens\n    while last_n_tokens >= keep_last_n_words:\n        last_n_tokens -= len(paragraphs[0].split(' '))\n        paragraphs = paragraphs[1:]\n    return '\\n' + '\\n'.join(paragraphs)\n\n\ndef get_new_image_name(org_img_name, func_name=\"update\"):\n    head_tail = os.path.split(org_img_name)\n    head = head_tail[0]\n    tail = head_tail[1]\n    name_split = tail.split('.')[0].split('_')\n    this_new_uuid = str(uuid.uuid4())[:4]\n    if len(name_split) == 1:\n        most_org_file_name = name_split[0]\n    else:\n        assert len(name_split) == 4\n        most_org_file_name = name_split[3]\n    recent_prev_file_name = name_split[0]\n    new_file_name = f'{this_new_uuid}_{func_name}_{recent_prev_file_name}_{most_org_file_name}.png'\n    return os.path.join(head, new_file_name)\n\nclass InstructPix2Pix:\n    def __init__(self, device):\n        print(f\"Initializing InstructPix2Pix to {device}\")\n        self.device = device\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n       \n        self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(\"timbrooks/instruct-pix2pix\",\n                                                                           safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n                                                                           torch_dtype=self.torch_dtype).to(device)\n        self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)\n\n    @prompts(name=\"Instruct Image Using Text\",\n             description=\"useful when you want to the style of the image to be like the text. \"\n                         \"like: make it look like a painting. or make it like a robot. \"\n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path and the text. \")\n    def inference(self, inputs):\n        \"\"\"Change style of image.\"\"\"\n        print(\"===>Starting InstructPix2Pix Inference\")\n        image_path, text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        original_image = Image.open(image_path)\n        image = self.pipe(text, image=original_image, num_inference_steps=40, image_guidance_scale=1.2).images[0]\n        updated_image_path = get_new_image_name(image_path, func_name=\"pix2pix\")\n        image.save(updated_image_path)\n        print(f\"\\nProcessed InstructPix2Pix, Input Image: {image_path}, Instruct Text: {text}, \"\n              f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\n\nclass Text2Image:\n    def __init__(self, device):\n        print(f\"Initializing Text2Image to {device}\")\n        self.device = device\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.pipe = StableDiffusionPipeline.from_pretrained(\"runwayml/stable-diffusion-v1-5\",\n                                                            torch_dtype=self.torch_dtype)\n        self.pipe.to(device)\n        self.a_prompt = 'best quality, extremely detailed'\n        self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n                        'fewer digits, cropped, worst quality, low quality'\n\n    @prompts(name=\"Generate Image From User Input Text\",\n             description=\"useful when you want to generate an image from a user input text and save it to a file. \"\n                         \"like: generate an image of an object or something, or generate an image that includes some objects. \"\n                         \"The input to this tool should be a string, representing the text used to generate image. \")\n    def inference(self, text):\n        image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")\n        prompt = text + ', ' + self.a_prompt\n        image = self.pipe(prompt, negative_prompt=self.n_prompt).images[0]\n        image.save(image_filename)\n        print(\n            f\"\\nProcessed Text2Image, Input Text: {text}, Output Image: {image_filename}\")\n        return image_filename\n\n\nclass ImageCaptioning:\n    def __init__(self, device):\n        print(f\"Initializing ImageCaptioning to {device}\")\n        self.device = device\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.processor = BlipProcessor.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n        self.model = BlipForConditionalGeneration.from_pretrained(\n            \"Salesforce/blip-image-captioning-base\", torch_dtype=self.torch_dtype).to(self.device)\n\n    @prompts(name=\"Get Photo Description\",\n             description=\"useful when you want to know what is inside the photo. receives image_path as input. \"\n                         \"The input to this tool should be a string, representing the image_path. \")\n    def inference(self, image_path):\n        inputs = self.processor(Image.open(image_path), return_tensors=\"pt\").to(self.device, self.torch_dtype)\n        out = self.model.generate(**inputs)\n        captions = self.processor.decode(out[0], skip_special_tokens=True)\n        print(f\"\\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}\")\n        return captions\n\n\nclass Image2Canny:\n    def __init__(self, device):\n        print(\"Initializing Image2Canny\")\n        self.low_threshold = 100\n        self.high_threshold = 200\n\n    @prompts(name=\"Edge Detection On Image\",\n             description=\"useful when you want to detect the edge of the image. \"\n                         \"like: detect the edges of this image, or canny detection on image, \"\n                         \"or perform edge detection on this image, or detect the canny image of this image. \"\n                         \"The input to this tool should be a string, representing the image_path\")\n    def inference(self, inputs):\n        image = Image.open(inputs)\n        image = np.array(image)\n        canny = cv2.Canny(image, self.low_threshold, self.high_threshold)\n        canny = canny[:, :, None]\n        canny = np.concatenate([canny, canny, canny], axis=2)\n        canny = Image.fromarray(canny)\n        updated_image_path = get_new_image_name(inputs, func_name=\"edge\")\n        canny.save(updated_image_path)\n        print(f\"\\nProcessed Image2Canny, Input Image: {inputs}, Output Text: {updated_image_path}\")\n        return updated_image_path\n\n\nclass CannyText2Image:\n    def __init__(self, device):\n        print(f\"Initializing CannyText2Image to {device}\")\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-canny\",\n                                                          torch_dtype=self.torch_dtype)\n        self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n            \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n            torch_dtype=self.torch_dtype)\n        self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n        self.pipe.to(device)\n        self.seed = -1\n        self.a_prompt = 'best quality, extremely detailed'\n        self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n                            'fewer digits, cropped, worst quality, low quality'\n\n    @prompts(name=\"Generate Image Condition On Canny Image\",\n             description=\"useful when you want to generate a new real image from both the user description and a canny image.\"\n                         \" like: generate a real image of a object or something from this canny image,\"\n                         \" or generate a new real image of a object or something from this edge image. \"\n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path and the user description. \")\n    def inference(self, inputs):\n        image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        image = Image.open(image_path)\n        self.seed = random.randint(0, 65535)\n        seed_everything(self.seed)\n        prompt = f'{instruct_text}, {self.a_prompt}'\n        image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n                          guidance_scale=9.0).images[0]\n        updated_image_path = get_new_image_name(image_path, func_name=\"canny2image\")\n        image.save(updated_image_path)\n        print(f\"\\nProcessed CannyText2Image, Input Canny: {image_path}, Input Text: {instruct_text}, \"\n              f\"Output Text: {updated_image_path}\")\n        return updated_image_path\n\n\nclass Image2Line:\n    def __init__(self, device):\n        print(\"Initializing Image2Line\")\n        self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')\n\n    @prompts(name=\"Line Detection On Image\",\n             description=\"useful when you want to detect the straight line of the image. \"\n                         \"like: detect the straight lines of this image, or straight line detection on image, \"\n                         \"or perform straight line detection on this image, or detect the straight line image of this image. \"\n                         \"The input to this tool should be a string, representing the image_path\")\n    def inference(self, inputs):\n        image = Image.open(inputs)\n        mlsd = self.detector(image)\n        updated_image_path = get_new_image_name(inputs, func_name=\"line-of\")\n        mlsd.save(updated_image_path)\n        print(f\"\\nProcessed Image2Line, Input Image: {inputs}, Output Line: {updated_image_path}\")\n        return updated_image_path\n\n\nclass LineText2Image:\n    def __init__(self, device):\n        print(f\"Initializing LineText2Image to {device}\")\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-mlsd\",\n                                                          torch_dtype=self.torch_dtype)\n        self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n            \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n            torch_dtype=self.torch_dtype\n        )\n        self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n        self.pipe.to(device)\n        self.seed = -1\n        self.a_prompt = 'best quality, extremely detailed'\n        self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n                            'fewer digits, cropped, worst quality, low quality'\n\n    @prompts(name=\"Generate Image Condition On Line Image\",\n             description=\"useful when you want to generate a new real image from both the user description \"\n                         \"and a straight line image. \"\n                         \"like: generate a real image of a object or something from this straight line image, \"\n                         \"or generate a new real image of a object or something from this straight lines. \"\n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path and the user description. \")\n    def inference(self, inputs):\n        image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        image = Image.open(image_path)\n        self.seed = random.randint(0, 65535)\n        seed_everything(self.seed)\n        prompt = f'{instruct_text}, {self.a_prompt}'\n        image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n                          guidance_scale=9.0).images[0]\n        updated_image_path = get_new_image_name(image_path, func_name=\"line2image\")\n        image.save(updated_image_path)\n        print(f\"\\nProcessed LineText2Image, Input Line: {image_path}, Input Text: {instruct_text}, \"\n              f\"Output Text: {updated_image_path}\")\n        return updated_image_path\n\n\nclass Image2Hed:\n    def __init__(self, device):\n        print(\"Initializing Image2Hed\")\n        self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')\n\n    @prompts(name=\"Hed Detection On Image\",\n             description=\"useful when you want to detect the soft hed boundary of the image. \"\n                         \"like: detect the soft hed boundary of this image, or hed boundary detection on image, \"\n                         \"or perform hed boundary detection on this image, or detect soft hed boundary image of this image. \"\n                         \"The input to this tool should be a string, representing the image_path\")\n    def inference(self, inputs):\n        image = Image.open(inputs)\n        hed = self.detector(image)\n        updated_image_path = get_new_image_name(inputs, func_name=\"hed-boundary\")\n        hed.save(updated_image_path)\n        print(f\"\\nProcessed Image2Hed, Input Image: {inputs}, Output Hed: {updated_image_path}\")\n        return updated_image_path\n\n\nclass HedText2Image:\n    def __init__(self, device):\n        print(f\"Initializing HedText2Image to {device}\")\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-hed\",\n                                                          torch_dtype=self.torch_dtype)\n        self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n            \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n            torch_dtype=self.torch_dtype\n        )\n        self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n        self.pipe.to(device)\n        self.seed = -1\n        self.a_prompt = 'best quality, extremely detailed'\n        self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n                            'fewer digits, cropped, worst quality, low quality'\n\n    @prompts(name=\"Generate Image Condition On Soft Hed Boundary Image\",\n             description=\"useful when you want to generate a new real image from both the user description \"\n                         \"and a soft hed boundary image. \"\n                         \"like: generate a real image of a object or something from this soft hed boundary image, \"\n                         \"or generate a new real image of a object or something from this hed boundary. \"\n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path and the user description\")\n    def inference(self, inputs):\n        image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        image = Image.open(image_path)\n        self.seed = random.randint(0, 65535)\n        seed_everything(self.seed)\n        prompt = f'{instruct_text}, {self.a_prompt}'\n        image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n                          guidance_scale=9.0).images[0]\n        updated_image_path = get_new_image_name(image_path, func_name=\"hed2image\")\n        image.save(updated_image_path)\n        print(f\"\\nProcessed HedText2Image, Input Hed: {image_path}, Input Text: {instruct_text}, \"\n              f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\n\nclass Image2Scribble:\n    def __init__(self, device):\n        print(\"Initializing Image2Scribble\")\n        self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')\n\n    @prompts(name=\"Sketch Detection On Image\",\n             description=\"useful when you want to generate a scribble of the image. \"\n                         \"like: generate a scribble of this image, or generate a sketch from this image, \"\n                         \"detect the sketch from this image. \"\n                         \"The input to this tool should be a string, representing the image_path\")\n    def inference(self, inputs):\n        image = Image.open(inputs)\n        scribble = self.detector(image, scribble=True)\n        updated_image_path = get_new_image_name(inputs, func_name=\"scribble\")\n        scribble.save(updated_image_path)\n        print(f\"\\nProcessed Image2Scribble, Input Image: {inputs}, Output Scribble: {updated_image_path}\")\n        return updated_image_path\n\n\nclass ScribbleText2Image:\n    def __init__(self, device):\n        print(f\"Initializing ScribbleText2Image to {device}\")\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-scribble\",\n                                                          torch_dtype=self.torch_dtype)\n        self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n            \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n            torch_dtype=self.torch_dtype\n        )\n        self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n        self.pipe.to(device)\n        self.seed = -1\n        self.a_prompt = 'best quality, extremely detailed'\n        self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n                            'fewer digits, cropped, worst quality, low quality'\n\n    @prompts(name=\"Generate Image Condition On Sketch Image\",\n             description=\"useful when you want to generate a new real image from both the user description and \"\n                         \"a scribble image or a sketch image. \"\n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path and the user description\")\n    def inference(self, inputs):\n        image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        image = Image.open(image_path)\n        self.seed = random.randint(0, 65535)\n        seed_everything(self.seed)\n        prompt = f'{instruct_text}, {self.a_prompt}'\n        image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n                          guidance_scale=9.0).images[0]\n        updated_image_path = get_new_image_name(image_path, func_name=\"scribble2image\")\n        image.save(updated_image_path)\n        print(f\"\\nProcessed ScribbleText2Image, Input Scribble: {image_path}, Input Text: {instruct_text}, \"\n              f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\n\nclass Image2Pose:\n    def __init__(self, device):\n        print(\"Initializing Image2Pose\")\n        self.detector = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')\n\n    @prompts(name=\"Pose Detection On Image\",\n             description=\"useful when you want to detect the human pose of the image. \"\n                         \"like: generate human poses of this image, or generate a pose image from this image. \"\n                         \"The input to this tool should be a string, representing the image_path\")\n    def inference(self, inputs):\n        image = Image.open(inputs)\n        pose = self.detector(image)\n        updated_image_path = get_new_image_name(inputs, func_name=\"human-pose\")\n        pose.save(updated_image_path)\n        print(f\"\\nProcessed Image2Pose, Input Image: {inputs}, Output Pose: {updated_image_path}\")\n        return updated_image_path\n\n\nclass PoseText2Image:\n    def __init__(self, device):\n        print(f\"Initializing PoseText2Image to {device}\")\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-openpose\",\n                                                          torch_dtype=self.torch_dtype)\n        self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n            \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n            torch_dtype=self.torch_dtype)\n        self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n        self.pipe.to(device)\n        self.num_inference_steps = 20\n        self.seed = -1\n        self.unconditional_guidance_scale = 9.0\n        self.a_prompt = 'best quality, extremely detailed'\n        self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n                            ' fewer digits, cropped, worst quality, low quality'\n\n    @prompts(name=\"Generate Image Condition On Pose Image\",\n             description=\"useful when you want to generate a new real image from both the user description \"\n                         \"and a human pose image. \"\n                         \"like: generate a real image of a human from this human pose image, \"\n                         \"or generate a new real image of a human from this pose. \"\n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path and the user description\")\n    def inference(self, inputs):\n        image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        image = Image.open(image_path)\n        self.seed = random.randint(0, 65535)\n        seed_everything(self.seed)\n        prompt = f'{instruct_text}, {self.a_prompt}'\n        image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n                          guidance_scale=9.0).images[0]\n        updated_image_path = get_new_image_name(image_path, func_name=\"pose2image\")\n        image.save(updated_image_path)\n        print(f\"\\nProcessed PoseText2Image, Input Pose: {image_path}, Input Text: {instruct_text}, \"\n              f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\nclass SegText2Image:\n    def __init__(self, device):\n        print(f\"Initializing SegText2Image to {device}\")\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-seg\",\n                                                          torch_dtype=self.torch_dtype)\n        self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n            \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n            torch_dtype=self.torch_dtype)\n        self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n        self.pipe.to(device)\n        self.seed = -1\n        self.a_prompt = 'best quality, extremely detailed'\n        self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n                            ' fewer digits, cropped, worst quality, low quality'\n\n    @prompts(name=\"Generate Image Condition On Segmentations\",\n             description=\"useful when you want to generate a new real image from both the user description and segmentations. \"\n                         \"like: generate a real image of a object or something from this segmentation image, \"\n                         \"or generate a new real image of a object or something from these segmentations. \"\n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path and the user description\")\n    def inference(self, inputs):\n        image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        image = Image.open(image_path)\n        self.seed = random.randint(0, 65535)\n        seed_everything(self.seed)\n        prompt = f'{instruct_text}, {self.a_prompt}'\n        image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n                          guidance_scale=9.0).images[0]\n        updated_image_path = get_new_image_name(image_path, func_name=\"segment2image\")\n        image.save(updated_image_path)\n        print(f\"\\nProcessed SegText2Image, Input Seg: {image_path}, Input Text: {instruct_text}, \"\n              f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\n\nclass Image2Depth:\n    def __init__(self, device):\n        print(\"Initializing Image2Depth\")\n        self.depth_estimator = pipeline('depth-estimation')\n\n    @prompts(name=\"Predict Depth On Image\",\n             description=\"useful when you want to detect depth of the image. like: generate the depth from this image, \"\n                         \"or detect the depth map on this image, or predict the depth for this image. \"\n                         \"The input to this tool should be a string, representing the image_path\")\n    def inference(self, inputs):\n        image = Image.open(inputs)\n        depth = self.depth_estimator(image)['depth']\n        depth = np.array(depth)\n        depth = depth[:, :, None]\n        depth = np.concatenate([depth, depth, depth], axis=2)\n        depth = Image.fromarray(depth)\n        updated_image_path = get_new_image_name(inputs, func_name=\"depth\")\n        depth.save(updated_image_path)\n        print(f\"\\nProcessed Image2Depth, Input Image: {inputs}, Output Depth: {updated_image_path}\")\n        return updated_image_path\n\n\nclass DepthText2Image:\n    def __init__(self, device):\n        print(f\"Initializing DepthText2Image to {device}\")\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.controlnet = ControlNetModel.from_pretrained(\n            \"fusing/stable-diffusion-v1-5-controlnet-depth\", torch_dtype=self.torch_dtype)\n        self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n            \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n            torch_dtype=self.torch_dtype)\n        self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n        self.pipe.to(device)\n        self.seed = -1\n        self.a_prompt = 'best quality, extremely detailed'\n        self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n                            ' fewer digits, cropped, worst quality, low quality'\n\n    @prompts(name=\"Generate Image Condition On Depth\",\n             description=\"useful when you want to generate a new real image from both the user description and depth image. \"\n                         \"like: generate a real image of a object or something from this depth image, \"\n                         \"or generate a new real image of a object or something from the depth map. \"\n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path and the user description\")\n    def inference(self, inputs):\n        image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        image = Image.open(image_path)\n        self.seed = random.randint(0, 65535)\n        seed_everything(self.seed)\n        prompt = f'{instruct_text}, {self.a_prompt}'\n        image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n                          guidance_scale=9.0).images[0]\n        updated_image_path = get_new_image_name(image_path, func_name=\"depth2image\")\n        image.save(updated_image_path)\n        print(f\"\\nProcessed DepthText2Image, Input Depth: {image_path}, Input Text: {instruct_text}, \"\n              f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\n\nclass Image2Normal:\n    def __init__(self, device):\n        print(\"Initializing Image2Normal\")\n        self.depth_estimator = pipeline(\"depth-estimation\", model=\"Intel/dpt-hybrid-midas\")\n        self.bg_threhold = 0.4\n\n    @prompts(name=\"Predict Normal Map On Image\",\n             description=\"useful when you want to detect norm map of the image. \"\n                         \"like: generate normal map from this image, or predict normal map of this image. \"\n                         \"The input to this tool should be a string, representing the image_path\")\n    def inference(self, inputs):\n        image = Image.open(inputs)\n        original_size = image.size\n        image = self.depth_estimator(image)['predicted_depth'][0]\n        image = image.numpy()\n        image_depth = image.copy()\n        image_depth -= np.min(image_depth)\n        image_depth /= np.max(image_depth)\n        x = cv2.Sobel(image, cv2.CV_32F, 1, 0, ksize=3)\n        x[image_depth < self.bg_threhold] = 0\n        y = cv2.Sobel(image, cv2.CV_32F, 0, 1, ksize=3)\n        y[image_depth < self.bg_threhold] = 0\n        z = np.ones_like(x) * np.pi * 2.0\n        image = np.stack([x, y, z], axis=2)\n        image /= np.sum(image ** 2.0, axis=2, keepdims=True) ** 0.5\n        image = (image * 127.5 + 127.5).clip(0, 255).astype(np.uint8)\n        image = Image.fromarray(image)\n        image = image.resize(original_size)\n        updated_image_path = get_new_image_name(inputs, func_name=\"normal-map\")\n        image.save(updated_image_path)\n        print(f\"\\nProcessed Image2Normal, Input Image: {inputs}, Output Depth: {updated_image_path}\")\n        return updated_image_path\n\n\nclass NormalText2Image:\n    def __init__(self, device):\n        print(f\"Initializing NormalText2Image to {device}\")\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.controlnet = ControlNetModel.from_pretrained(\n            \"fusing/stable-diffusion-v1-5-controlnet-normal\", torch_dtype=self.torch_dtype)\n        self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n            \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n            torch_dtype=self.torch_dtype)\n        self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n        self.pipe.to(device)\n        self.seed = -1\n        self.a_prompt = 'best quality, extremely detailed'\n        self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n                            ' fewer digits, cropped, worst quality, low quality'\n\n    @prompts(name=\"Generate Image Condition On Normal Map\",\n             description=\"useful when you want to generate a new real image from both the user description and normal map. \"\n                         \"like: generate a real image of a object or something from this normal map, \"\n                         \"or generate a new real image of a object or something from the normal map. \"\n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path and the user description\")\n    def inference(self, inputs):\n        image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        image = Image.open(image_path)\n        self.seed = random.randint(0, 65535)\n        seed_everything(self.seed)\n        prompt = f'{instruct_text}, {self.a_prompt}'\n        image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n                          guidance_scale=9.0).images[0]\n        updated_image_path = get_new_image_name(image_path, func_name=\"normal2image\")\n        image.save(updated_image_path)\n        print(f\"\\nProcessed NormalText2Image, Input Normal: {image_path}, Input Text: {instruct_text}, \"\n              f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\n\nclass VisualQuestionAnswering:\n    def __init__(self, device):\n        print(f\"Initializing VisualQuestionAnswering to {device}\")\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.device = device\n        self.processor = BlipProcessor.from_pretrained(\"Salesforce/blip-vqa-base\")\n        self.model = BlipForQuestionAnswering.from_pretrained(\n            \"Salesforce/blip-vqa-base\", torch_dtype=self.torch_dtype).to(self.device)\n\n    @prompts(name=\"Answer Question About The Image\",\n             description=\"useful when you need an answer for a question based on an image. \"\n                         \"like: what is the background color of the last image, how many cats in this figure, what is in this figure. \"\n                         \"The input to this tool should be a comma separated string of two, representing the image_path and the question\")\n    def inference(self, inputs):\n        image_path, question = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        raw_image = Image.open(image_path).convert('RGB')\n        inputs = self.processor(raw_image, question, return_tensors=\"pt\").to(self.device, self.torch_dtype)\n        out = self.model.generate(**inputs)\n        answer = self.processor.decode(out[0], skip_special_tokens=True)\n        print(f\"\\nProcessed VisualQuestionAnswering, Input Image: {image_path}, Input Question: {question}, \"\n              f\"Output Answer: {answer}\")\n        return answer\n\n\nclass Segmenting:\n    def __init__(self, device):\n        print(f\"Inintializing Segmentation to {device}\")\n        self.device = device\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.model_checkpoint_path = os.path.join(\"checkpoints\",\"sam\")\n\n        self.download_parameters()\n        self.sam = build_sam(checkpoint=self.model_checkpoint_path).to(device)\n        self.sam_predictor = SamPredictor(self.sam)\n        self.mask_generator = SamAutomaticMaskGenerator(self.sam)\n        \n        self.saved_points = []\n        self.saved_labels = []\n\n    def download_parameters(self):\n        url = \"https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth\"\n        if not os.path.exists(self.model_checkpoint_path):\n            wget.download(url,out=self.model_checkpoint_path)\n\n        \n    def show_mask(self, mask: np.ndarray,image: np.ndarray,\n                random_color: bool = False, transparency=1) -> np.ndarray:\n        \n        \"\"\"Visualize a mask on top of an image.\n        Args:\n            mask (np.ndarray): A 2D array of shape (H, W).\n            image (np.ndarray): A 3D array of shape (H, W, 3).\n            random_color (bool): Whether to use a random color for the mask.\n        Outputs:\n            np.ndarray: A 3D array of shape (H, W, 3) with the mask\n            visualized on top of the image.\n            transparenccy: the transparency of the segmentation mask\n        \"\"\"\n        \n        if random_color:\n            color = np.concatenate([np.random.random(3)], axis=0)\n        else:\n            color = np.array([30 / 255, 144 / 255, 255 / 255])\n        h, w = mask.shape[-2:]\n        mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1) * 255\n\n        image = cv2.addWeighted(image, 0.7, mask_image.astype('uint8'), transparency, 0)\n\n\n        return image\n\n    def show_box(self, box, ax, label):\n        x0, y0 = box[0], box[1]\n        w, h = box[2] - box[0], box[3] - box[1]\n        ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2)) \n        ax.text(x0, y0, label)\n\n    \n    def get_mask_with_boxes(self, image_pil, image, boxes_filt):\n\n        size = image_pil.size\n        H, W = size[1], size[0]\n        for i in range(boxes_filt.size(0)):\n            boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])\n            boxes_filt[i][:2] -= boxes_filt[i][2:] / 2\n            boxes_filt[i][2:] += boxes_filt[i][:2]\n\n        boxes_filt = boxes_filt.cpu()\n        transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(self.device)\n\n        masks, _, _ = self.sam_predictor.predict_torch(\n            point_coords = None,\n            point_labels = None,\n            boxes = transformed_boxes.to(self.device),\n            multimask_output = False,\n        )\n        return masks\n    \n    def segment_image_with_boxes(self, image_pil, image_path, boxes_filt, pred_phrases):\n\n        image = cv2.imread(image_path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        self.sam_predictor.set_image(image)\n\n        masks = self.get_mask_with_boxes(image_pil, image, boxes_filt)\n\n        # draw output image\n\n        for mask in masks:\n            image = self.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)\n\n        updated_image_path = get_new_image_name(image_path, func_name=\"segmentation\")\n        \n        new_image = Image.fromarray(image)\n        new_image.save(updated_image_path)\n\n        return updated_image_path\n\n    def set_image(self, img) -> None:\n        \"\"\"Set the image for the predictor.\"\"\"\n        with torch.cuda.amp.autocast():\n            self.sam_predictor.set_image(img)\n\n    def show_points(self, coords: np.ndarray, labels: np.ndarray,\n                image: np.ndarray) -> np.ndarray:\n        \"\"\"Visualize points on top of an image.\n\n        Args:\n            coords (np.ndarray): A 2D array of shape (N, 2).\n            labels (np.ndarray): A 1D array of shape (N,).\n            image (np.ndarray): A 3D array of shape (H, W, 3).\n        Returns:\n            np.ndarray: A 3D array of shape (H, W, 3) with the points\n            visualized on top of the image.\n        \"\"\"\n        pos_points = coords[labels == 1]\n        neg_points = coords[labels == 0]\n        for p in pos_points:\n            image = cv2.circle(\n                image, p.astype(int), radius=3, color=(0, 255, 0), thickness=-1)\n        for p in neg_points:\n            image = cv2.circle(\n                image, p.astype(int), radius=3, color=(255, 0, 0), thickness=-1)\n        return image\n\n\n    def segment_image_with_click(self, img, is_positive: bool,\n                            evt: gr.SelectData):\n                            \n        self.sam_predictor.set_image(img)\n        self.saved_points.append([evt.index[0], evt.index[1]])\n        self.saved_labels.append(1 if is_positive else 0)\n        input_point = np.array(self.saved_points)\n        input_label = np.array(self.saved_labels)\n        \n        # Predict the mask\n        with torch.cuda.amp.autocast():\n            masks, scores, logits = self.sam_predictor.predict(\n                point_coords=input_point,\n                point_labels=input_label,\n                multimask_output=False,\n            )\n\n        img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)\n\n        img = self.show_points(input_point, input_label, img)\n\n        return img\n\n    def segment_image_with_coordinate(self, img, is_positive: bool,\n                            coordinate: tuple):\n        '''\n            Args:\n                img (numpy.ndarray): the given image, shape: H x W x 3.\n                is_positive: whether the click is positive, if want to add mask use True else False.\n                coordinate: the position of the click\n                          If the position is (x,y), means click at the x-th column and y-th row of the pixel matrix.\n                          So x correspond to W, and y correspond to H.\n            Output:\n                img (PLI.Image.Image): the result image\n                result_mask (numpy.ndarray): the result mask, shape: H x W\n\n            Other parameters:\n                transparency (float): the transparenccy of the mask\n                                      to control he degree of transparency after the mask is superimposed.\n                                      if transparency=1, then the masked part will be completely replaced with other colors.\n        '''\n        self.sam_predictor.set_image(img)\n        self.saved_points.append([coordinate[0], coordinate[1]])\n        self.saved_labels.append(1 if is_positive else 0)\n        input_point = np.array(self.saved_points)\n        input_label = np.array(self.saved_labels)\n\n        # Predict the mask\n        with torch.cuda.amp.autocast():\n            masks, scores, logits = self.sam_predictor.predict(\n                point_coords=input_point,\n                point_labels=input_label,\n                multimask_output=False,\n            )\n\n\n        img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)\n\n        img = self.show_points(input_point, input_label, img)\n\n        img = Image.fromarray(img)\n        \n        result_mask = masks[0]\n\n        return img, result_mask\n\n    @prompts(name=\"Segment the Image\",\n             description=\"useful when you want to segment all the part of the image, but not segment a certain object.\"\n                         \"like: segment all the object in this image, or generate segmentations on this image, \"\n                         \"or segment the image,\"\n                         \"or perform segmentation on this image, \"\n                         \"or segment all the object in this image.\"\n                         \"The input to this tool should be a string, representing the image_path\")\n    def inference_all(self,image_path):\n        image = cv2.imread(image_path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        masks = self.mask_generator.generate(image)\n        plt.figure(figsize=(20,20))\n        plt.imshow(image)\n        if len(masks) == 0:\n            return\n        sorted_anns = sorted(masks, key=(lambda x: x['area']), reverse=True)\n        ax = plt.gca()\n        ax.set_autoscale_on(False)\n        polygons = []\n        color = []\n        for ann in sorted_anns:\n            m = ann['segmentation']\n            img = np.ones((m.shape[0], m.shape[1], 3))\n            color_mask = np.random.random((1, 3)).tolist()[0]\n            for i in range(3):\n                img[:,:,i] = color_mask[i]\n            ax.imshow(np.dstack((img, m)))\n\n        updated_image_path = get_new_image_name(image_path, func_name=\"segment-image\")\n        plt.axis('off')\n        plt.savefig(\n            updated_image_path, \n            bbox_inches=\"tight\", dpi=300, pad_inches=0.0\n        )\n        return updated_image_path\n    \nclass Text2Box:\n    def __init__(self, device):\n        print(f\"Initializing ObjectDetection to {device}\")\n        self.device = device\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n        self.model_checkpoint_path = os.path.join(\"checkpoints\",\"groundingdino\")\n        self.model_config_path = os.path.join(\"checkpoints\",\"grounding_config.py\")\n        self.download_parameters()\n        self.box_threshold = 0.3\n        self.text_threshold = 0.25\n        self.grounding = (self.load_model()).to(self.device)\n\n    def download_parameters(self):\n        url = \"https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth\"\n        if not os.path.exists(self.model_checkpoint_path):\n            wget.download(url,out=self.model_checkpoint_path)\n        config_url = \"https://raw.githubusercontent.com/IDEA-Research/GroundingDINO/main/groundingdino/config/GroundingDINO_SwinT_OGC.py\"\n        if not os.path.exists(self.model_config_path):\n            wget.download(config_url,out=self.model_config_path)\n    def load_image(self,image_path):\n         # load image\n        image_pil = Image.open(image_path).convert(\"RGB\")  # load image\n\n        transform = T.Compose(\n            [\n                T.RandomResize([512], max_size=1333),\n                T.ToTensor(),\n                T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n            ]\n        )\n        image, _ = transform(image_pil, None)  # 3, h, w\n        return image_pil, image\n\n    def load_model(self):\n        args = SLConfig.fromfile(self.model_config_path)\n        args.device = self.device\n        model = build_model(args)\n        checkpoint = torch.load(self.model_checkpoint_path, map_location=\"cpu\")\n        load_res = model.load_state_dict(clean_state_dict(checkpoint[\"model\"]), strict=False)\n        print(load_res)\n        _ = model.eval()\n        return model\n\n    def get_grounding_boxes(self, image, caption, with_logits=True):\n        caption = caption.lower()\n        caption = caption.strip()\n        if not caption.endswith(\".\"):\n            caption = caption + \".\"\n        image = image.to(self.device)\n        with torch.no_grad():\n            outputs = self.grounding(image[None], captions=[caption])\n        logits = outputs[\"pred_logits\"].cpu().sigmoid()[0]  # (nq, 256)\n        boxes = outputs[\"pred_boxes\"].cpu()[0]  # (nq, 4)\n        logits.shape[0]\n\n        # filter output\n        logits_filt = logits.clone()\n        boxes_filt = boxes.clone()\n        filt_mask = logits_filt.max(dim=1)[0] > self.box_threshold\n        logits_filt = logits_filt[filt_mask]  # num_filt, 256\n        boxes_filt = boxes_filt[filt_mask]  # num_filt, 4\n        logits_filt.shape[0]\n\n        # get phrase\n        tokenlizer = self.grounding.tokenizer\n        tokenized = tokenlizer(caption)\n        # build pred\n        pred_phrases = []\n        for logit, box in zip(logits_filt, boxes_filt):\n            pred_phrase = get_phrases_from_posmap(logit > self.text_threshold, tokenized, tokenlizer)\n            if with_logits:\n                pred_phrases.append(pred_phrase + f\"({str(logit.max().item())[:4]})\")\n            else:\n                pred_phrases.append(pred_phrase)\n\n        return boxes_filt, pred_phrases\n    \n    def plot_boxes_to_image(self, image_pil, tgt):\n        H, W = tgt[\"size\"]\n        boxes = tgt[\"boxes\"]\n        labels = tgt[\"labels\"]\n        assert len(boxes) == len(labels), \"boxes and labels must have same length\"\n\n        draw = ImageDraw.Draw(image_pil)\n        mask = Image.new(\"L\", image_pil.size, 0)\n        mask_draw = ImageDraw.Draw(mask)\n\n        # draw boxes and masks\n        for box, label in zip(boxes, labels):\n            # from 0..1 to 0..W, 0..H\n            box = box * torch.Tensor([W, H, W, H])\n            # from xywh to xyxy\n            box[:2] -= box[2:] / 2\n            box[2:] += box[:2]\n            # random color\n            color = tuple(np.random.randint(0, 255, size=3).tolist())\n            # draw\n            x0, y0, x1, y1 = box\n            x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)\n\n            draw.rectangle([x0, y0, x1, y1], outline=color, width=6)\n            # draw.text((x0, y0), str(label), fill=color)\n\n            font = ImageFont.load_default()\n            if hasattr(font, \"getbbox\"):\n                bbox = draw.textbbox((x0, y0), str(label), font)\n            else:\n                w, h = draw.textsize(str(label), font)\n                bbox = (x0, y0, w + x0, y0 + h)\n            # bbox = draw.textbbox((x0, y0), str(label))\n            draw.rectangle(bbox, fill=color)\n            draw.text((x0, y0), str(label), fill=\"white\")\n\n            mask_draw.rectangle([x0, y0, x1, y1], fill=255, width=2)\n\n        return image_pil, mask\n    \n    @prompts(name=\"Detect the Give Object\",\n             description=\"useful when you only want to detect or find out given objects in the picture\"  \n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path, the text description of the object to be found\")\n    def inference(self, inputs):\n        image_path, det_prompt = inputs.split(\",\")\n        print(f\"image_path={image_path}, text_prompt={det_prompt}\")\n        image_pil, image = self.load_image(image_path)\n\n        boxes_filt, pred_phrases = self.get_grounding_boxes(image, det_prompt)\n\n        size = image_pil.size\n        pred_dict = {\n        \"boxes\": boxes_filt,\n        \"size\": [size[1], size[0]],  # H,W\n        \"labels\": pred_phrases,}\n\n        image_with_box = self.plot_boxes_to_image(image_pil, pred_dict)[0]\n\n        updated_image_path = get_new_image_name(image_path, func_name=\"detect-something\")\n        updated_image = image_with_box.resize(size)\n        updated_image.save(updated_image_path)\n        print(\n            f\"\\nProcessed ObejectDetecting, Input Image: {image_path}, Object to be Detect {det_prompt}, \"\n            f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\n\nclass Inpainting:\n    def __init__(self, device):\n        self.device = device\n        self.revision = 'fp16' if 'cuda' in self.device else None\n        self.torch_dtype = torch.float16 if 'cuda' in self.device else torch.float32\n\n        self.inpaint = StableDiffusionInpaintPipeline.from_pretrained(\n            \"runwayml/stable-diffusion-inpainting\", revision=self.revision, torch_dtype=self.torch_dtype,safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker')).to(device)\n    def __call__(self, prompt, image, mask_image, height=512, width=512, num_inference_steps=50):\n        update_image = self.inpaint(prompt=prompt, image=image.resize((width, height)),\n                                     mask_image=mask_image.resize((width, height)), height=height, width=width, num_inference_steps=num_inference_steps).images[0]\n        return update_image\n\nclass InfinityOutPainting:\n    template_model = True # Add this line to show this is a template model.\n    def __init__(self, ImageCaptioning, Inpainting, VisualQuestionAnswering):\n        self.llm = OpenAI(temperature=0)\n        self.ImageCaption = ImageCaptioning\n        self.inpaint = Inpainting\n        self.ImageVQA = VisualQuestionAnswering\n        self.a_prompt = 'best quality, extremely detailed'\n        self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n                        'fewer digits, cropped, worst quality, low quality'\n\n    def get_BLIP_vqa(self, image, question):\n        inputs = self.ImageVQA.processor(image, question, return_tensors=\"pt\").to(self.ImageVQA.device,\n                                                                                  self.ImageVQA.torch_dtype)\n        out = self.ImageVQA.model.generate(**inputs)\n        answer = self.ImageVQA.processor.decode(out[0], skip_special_tokens=True)\n        print(f\"\\nProcessed VisualQuestionAnswering, Input Question: {question}, Output Answer: {answer}\")\n        return answer\n\n    def get_BLIP_caption(self, image):\n        inputs = self.ImageCaption.processor(image, return_tensors=\"pt\").to(self.ImageCaption.device,\n                                                                                self.ImageCaption.torch_dtype)\n        out = self.ImageCaption.model.generate(**inputs)\n        BLIP_caption = self.ImageCaption.processor.decode(out[0], skip_special_tokens=True)\n        return BLIP_caption\n\n    def check_prompt(self, prompt):\n        check = f\"Here is a paragraph with adjectives. \" \\\n                f\"{prompt} \" \\\n                f\"Please change all plural forms in the adjectives to singular forms. \"\n        return self.llm(check)\n\n    def get_imagine_caption(self, image, imagine):\n        BLIP_caption = self.get_BLIP_caption(image)\n        background_color = self.get_BLIP_vqa(image, 'what is the background color of this image')\n        style = self.get_BLIP_vqa(image, 'what is the style of this image')\n        imagine_prompt = f\"let's pretend you are an excellent painter and now \" \\\n                         f\"there is an incomplete painting with {BLIP_caption} in the center, \" \\\n                         f\"please imagine the complete painting and describe it\" \\\n                         f\"you should consider the background color is {background_color}, the style is {style}\" \\\n                         f\"You should make the painting as vivid and realistic as possible\" \\\n                         f\"You can not use words like painting or picture\" \\\n                         f\"and you should use no more than 50 words to describe it\"\n        caption = self.llm(imagine_prompt) if imagine else BLIP_caption\n        caption = self.check_prompt(caption)\n        print(f'BLIP observation: {BLIP_caption}, ChatGPT imagine to {caption}') if imagine else print(\n            f'Prompt: {caption}')\n        return caption\n\n    def resize_image(self, image, max_size=1000000, multiple=8):\n        aspect_ratio = image.size[0] / image.size[1]\n        new_width = int(math.sqrt(max_size * aspect_ratio))\n        new_height = int(new_width / aspect_ratio)\n        new_width, new_height = new_width - (new_width % multiple), new_height - (new_height % multiple)\n        return image.resize((new_width, new_height))\n\n    def dowhile(self, original_img, tosize, expand_ratio, imagine, usr_prompt):\n        old_img = original_img\n        while (old_img.size != tosize):\n            prompt = self.check_prompt(usr_prompt) if usr_prompt else self.get_imagine_caption(old_img, imagine)\n            crop_w = 15 if old_img.size[0] != tosize[0] else 0\n            crop_h = 15 if old_img.size[1] != tosize[1] else 0\n            old_img = ImageOps.crop(old_img, (crop_w, crop_h, crop_w, crop_h))\n            temp_canvas_size = (expand_ratio * old_img.width if expand_ratio * old_img.width < tosize[0] else tosize[0],\n                                expand_ratio * old_img.height if expand_ratio * old_img.height < tosize[1] else tosize[\n                                    1])\n            temp_canvas, temp_mask = Image.new(\"RGB\", temp_canvas_size, color=\"white\"), Image.new(\"L\", temp_canvas_size,\n                                                                                                  color=\"white\")\n            x, y = (temp_canvas.width - old_img.width) // 2, (temp_canvas.height - old_img.height) // 2\n            temp_canvas.paste(old_img, (x, y))\n            temp_mask.paste(0, (x, y, x + old_img.width, y + old_img.height))\n            resized_temp_canvas, resized_temp_mask = self.resize_image(temp_canvas), self.resize_image(temp_mask)\n            image = self.inpaint(prompt=prompt, image=resized_temp_canvas, mask_image=resized_temp_mask,\n                                              height=resized_temp_canvas.height, width=resized_temp_canvas.width,\n                                              num_inference_steps=50).resize(\n                (temp_canvas.width, temp_canvas.height), Image.ANTIALIAS)\n            image = blend_gt2pt(old_img, image)\n            old_img = image\n        return old_img\n\n    @prompts(name=\"Extend An Image\",\n             description=\"useful when you need to extend an image into a larger image.\"\n                         \"like: extend the image into a resolution of 2048x1024, extend the image into 2048x1024. \"\n                         \"The input to this tool should be a comma separated string of two, representing the image_path and the resolution of widthxheight\")\n    def inference(self, inputs):\n        image_path, resolution = inputs.split(',')\n        width, height = resolution.split('x')\n        tosize = (int(width), int(height))\n        image = Image.open(image_path)\n        image = ImageOps.crop(image, (10, 10, 10, 10))\n        out_painted_image = self.dowhile(image, tosize, 4, True, False)\n        updated_image_path = get_new_image_name(image_path, func_name=\"outpainting\")\n        out_painted_image.save(updated_image_path)\n        print(f\"\\nProcessed InfinityOutPainting, Input Image: {image_path}, Input Resolution: {resolution}, \"\n              f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\n\n\nclass ObjectSegmenting:\n    template_model = True # Add this line to show this is a template model.\n    def __init__(self,  Text2Box:Text2Box, Segmenting:Segmenting):\n        # self.llm = OpenAI(temperature=0)\n        self.grounding = Text2Box\n        self.sam = Segmenting\n\n\n    @prompts(name=\"Segment the given object\",\n            description=\"useful when you only want to segment the certain objects in the picture\"\n                        \"according to the given text\"  \n                        \"like: segment the cat,\"\n                        \"or can you segment an obeject for me\"\n                        \"The input to this tool should be a comma separated string of two, \"\n                        \"representing the image_path, the text description of the object to be found\")\n    def inference(self, inputs):\n        image_path, det_prompt = inputs.split(\",\")\n        print(f\"image_path={image_path}, text_prompt={det_prompt}\")\n        image_pil, image = self.grounding.load_image(image_path)\n\n        boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, det_prompt)\n        updated_image_path = self.sam.segment_image_with_boxes(image_pil,image_path,boxes_filt,pred_phrases)\n        print(\n            f\"\\nProcessed ObejectSegmenting, Input Image: {image_path}, Object to be Segment {det_prompt}, \"\n            f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\n    def merge_masks(self, masks):\n        '''\n            Args:\n                mask (numpy.ndarray): shape N x 1 x H x W\n            Outputs:\n                new_mask (numpy.ndarray): shape H x W       \n        '''\n        if type(masks) == torch.Tensor:\n            x = masks\n        elif type(masks) == np.ndarray:\n            x = torch.tensor(masks,dtype=int)\n        else:   \n            raise TypeError(\"the type of the input masks must be numpy.ndarray or torch.tensor\")\n        x = x.squeeze(dim=1)\n        value, _ = x.max(dim=0)\n        new_mask = value.cpu().numpy()\n        new_mask.astype(np.uint8)\n        return new_mask\n    \n    def get_mask(self, image_path, text_prompt):\n\n        print(f\"image_path={image_path}, text_prompt={text_prompt}\")\n        # image_pil (PIL.Image.Image) -> size: W x H\n        # image (numpy.ndarray) -> H x W x 3\n        image_pil, image = self.grounding.load_image(image_path)\n\n        boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, text_prompt)\n        image = cv2.imread(image_path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        self.sam.sam_predictor.set_image(image)\n        \n        # masks (torch.tensor) -> N x 1 x H x W \n        masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)\n\n        # merged_mask -> H x W\n        merged_mask = self.merge_masks(masks)\n        # draw output image\n\n        for mask in masks:\n            image = self.sam.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)\n\n\n        merged_mask_image = Image.fromarray(merged_mask)\n\n        return merged_mask\n\n\nclass ImageEditing:\n    template_model = True\n    def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting, Inpainting:Inpainting):\n        print(f\"Initializing ImageEditing\")\n        self.sam = Segmenting\n        self.grounding = Text2Box\n        self.inpaint = Inpainting\n\n    def pad_edge(self,mask,padding):\n        #mask Tensor [H,W]\n        mask = mask.numpy()\n        true_indices = np.argwhere(mask)\n        mask_array = np.zeros_like(mask, dtype=bool)\n        for idx in true_indices:\n            padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)\n            mask_array[padded_slice] = True\n        new_mask = (mask_array * 255).astype(np.uint8)\n        #new_mask\n        return new_mask\n\n    @prompts(name=\"Remove Something From The Photo\",\n             description=\"useful when you want to remove and object or something from the photo \"\n                         \"from its description or location. \"\n                         \"The input to this tool should be a comma separated string of two, \"\n                         \"representing the image_path and the object need to be removed. \")    \n    def inference_remove(self, inputs):\n        image_path, to_be_removed_txt = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n        return self.inference_replace_sam(f\"{image_path},{to_be_removed_txt},background\")\n\n    @prompts(name=\"Replace Something From The Photo\",\n            description=\"useful when you want to replace an object from the object description or \"\n                        \"location with another object from its description. \"\n                        \"The input to this tool should be a comma separated string of three, \"\n                        \"representing the image_path, the object to be replaced, the object to be replaced with \")\n    def inference_replace_sam(self,inputs):\n        image_path, to_be_replaced_txt, replace_with_txt = inputs.split(\",\")\n        \n        print(f\"image_path={image_path}, to_be_replaced_txt={to_be_replaced_txt}\")\n        image_pil, image = self.grounding.load_image(image_path)\n        boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, to_be_replaced_txt)\n        image = cv2.imread(image_path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        self.sam.sam_predictor.set_image(image)\n        masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)\n        mask = torch.sum(masks, dim=0).unsqueeze(0)\n        mask = torch.where(mask > 0, True, False)\n        mask = mask.squeeze(0).squeeze(0).cpu() #tensor\n\n        mask = self.pad_edge(mask,padding=20) #numpy\n        mask_image = Image.fromarray(mask)\n\n        updated_image = self.inpaint(prompt=replace_with_txt, image=image_pil,\n                                     mask_image=mask_image)\n        updated_image_path = get_new_image_name(image_path, func_name=\"replace-something\")\n        updated_image = updated_image.resize(image_pil.size)\n        updated_image.save(updated_image_path)\n        print(\n            f\"\\nProcessed ImageEditing, Input Image: {image_path}, Replace {to_be_replaced_txt} to {replace_with_txt}, \"\n            f\"Output Image: {updated_image_path}\")\n        return updated_image_path\n\nclass BackgroundRemoving:\n    '''\n        using to remove the background of the given picture\n    '''\n    template_model = True\n    def __init__(self,VisualQuestionAnswering:VisualQuestionAnswering, Text2Box:Text2Box, Segmenting:Segmenting):\n        self.vqa = VisualQuestionAnswering\n        self.obj_segmenting = ObjectSegmenting(Text2Box,Segmenting)\n\n    @prompts(name=\"Remove the background\",\n             description=\"useful when you want to extract the object or remove the background,\"\n                         \"the input should be a string image_path\"\n                                )\n    def inference(self, image_path):\n        '''\n            given a image, return the picture only contains the extracted main object\n        '''\n        updated_image_path = None\n\n        mask = self.get_mask(image_path)\n\n        image = Image.open(image_path)\n        mask = Image.fromarray(mask)\n        image.putalpha(mask)\n\n        updated_image_path = get_new_image_name(image_path, func_name=\"detect-something\")\n        image.save(updated_image_path)\n\n        return updated_image_path\n\n    def get_mask(self, image_path):\n        '''\n            Description:\n                given an image path, return the mask of the main object.\n            Args:\n                image_path (string): the file path of the image\n            Outputs:\n                mask (numpy.ndarray): H x W\n        '''\n        vqa_input = f\"{image_path}, what is the main object in the image?\"\n        text_prompt = self.vqa.inference(vqa_input)\n\n        mask = self.obj_segmenting.get_mask(image_path,text_prompt)\n\n        return mask\n\n\nclass ConversationBot:\n    def __init__(self, load_dict):\n        # load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}\n        print(f\"Initializing VisualChatGPT, load_dict={load_dict}\")\n        if 'ImageCaptioning' not in load_dict:\n            raise ValueError(\"You have to load ImageCaptioning as a basic function for VisualChatGPT\")\n\n        self.models = {}\n        # Load Basic Foundation Models\n        for class_name, device in load_dict.items():\n            self.models[class_name] = globals()[class_name](device=device)\n\n        # Load Template Foundation Models\n        for class_name, module in globals().items():\n            if getattr(module, 'template_model', False):\n                template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if k!='self'}\n                loaded_names = set([type(e).__name__ for e in self.models.values()])\n                if template_required_names.issubset(loaded_names):\n                    self.models[class_name] = globals()[class_name](\n                        **{name: self.models[name] for name in template_required_names})\n        \n        print(f\"All the Available Functions: {self.models}\")\n\n        self.tools = []\n        for instance in self.models.values():\n            for e in dir(instance):\n                if e.startswith('inference'):\n                    func = getattr(instance, e)\n                    self.tools.append(Tool(name=func.name, description=func.description, func=func))\n        self.llm = OpenAI(temperature=0)\n        self.memory = ConversationBufferMemory(memory_key=\"chat_history\", output_key='output')\n\n    def init_agent(self, lang):\n        self.memory.clear() #clear previous history\n        if lang=='English':\n            PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, VISUAL_CHATGPT_SUFFIX\n            place = \"Enter text and press enter, or upload an image\"\n            label_clear = \"Clear\"\n        else:\n            PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX_CN, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN, VISUAL_CHATGPT_SUFFIX_CN\n            place = \"输入文字并回车，或者上传图片\"\n            label_clear = \"清除\"\n        self.agent = initialize_agent(\n            self.tools,\n            self.llm,\n            agent=\"conversational-react-description\",\n            verbose=True,\n            memory=self.memory,\n            return_intermediate_steps=True,\n            agent_kwargs={'prefix': PREFIX, 'format_instructions': FORMAT_INSTRUCTIONS,\n                          'suffix': SUFFIX}, )\n        return gr.update(visible = True), gr.update(visible = False), gr.update(placeholder=place), gr.update(value=label_clear)\n\n    def run_text(self, text, state):\n        self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)\n        res = self.agent({\"input\": text.strip()})\n        res['output'] = res['output'].replace(\"\\\\\", \"/\")\n        response = re.sub('(image/[-\\w]*.png)', lambda m: f'![](file={m.group(0)})*{m.group(0)}*', res['output'])\n        state = state + [(text, response)]\n        print(f\"\\nProcessed run_text, Input text: {text}\\nCurrent state: {state}\\n\"\n              f\"Current Memory: {self.agent.memory.buffer}\")\n        return state, state\n\n    def run_image(self, image, state, txt, lang):\n        image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")\n        print(\"======>Auto Resize Image...\")\n        img = Image.open(image.name)\n        width, height = img.size\n        ratio = min(512 / width, 512 / height)\n        width_new, height_new = (round(width * ratio), round(height * ratio))\n        width_new = int(np.round(width_new / 64.0)) * 64\n        height_new = int(np.round(height_new / 64.0)) * 64\n        img = img.resize((width_new, height_new))\n        img = img.convert('RGB')\n        img.save(image_filename, \"PNG\")\n        print(f\"Resize image form {width}x{height} to {width_new}x{height_new}\")\n        description = self.models['ImageCaptioning'].inference(image_filename)\n        if lang == 'Chinese':\n            Human_prompt = f'\\nHuman: 提供一张名为 {image_filename}的图片。它的描述是: {description}。 这些信息帮助你理解这个图像，但是你应该使用工具来完成下面的任务，而不是直接从我的描述中想象。 如果你明白了, 说 \\\"收到\\\". \\n'\n            AI_prompt = \"收到。  \"\n        else:\n            Human_prompt = f'\\nHuman: provide a figure named {image_filename}. The description is: {description}. This information helps you to understand this image, but you should use tools to finish following tasks, rather than directly imagine from my description. If you understand, say \\\"Received\\\". \\n'\n            AI_prompt = \"Received.  \"\n        self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt\n        state = state + [(f\"![](file={image_filename})*{image_filename}*\", AI_prompt)]\n        print(f\"\\nProcessed run_image, Input image: {image_filename}\\nCurrent state: {state}\\n\"\n              f\"Current Memory: {self.agent.memory.buffer}\")\n        return state, state, f'{txt} {image_filename} '\n\n\nif __name__ == '__main__':\n    if not os.path.exists(\"checkpoints\"):\n        os.mkdir(\"checkpoints\")\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--load', type=str, default=\"ImageCaptioning_cuda:0,Text2Image_cuda:0\")\n    args = parser.parse_args()\n    load_dict = {e.split('_')[0].strip(): e.split('_')[1].strip() for e in args.load.split(',')}\n    bot = ConversationBot(load_dict=load_dict)\n    with gr.Blocks(css=\"#chatbot .overflow-y-auto{height:500px}\") as demo:\n        lang = gr.Radio(choices = ['Chinese','English'], value=None, label='Language')\n        chatbot = gr.Chatbot(elem_id=\"chatbot\", label=\"Visual ChatGPT\")\n        state = gr.State([])\n        with gr.Row(visible=False) as input_raws:\n            with gr.Column(scale=0.7):\n                txt = gr.Textbox(show_label=False, placeholder=\"Enter text and press enter, or upload an image\").style(\n                    container=False)\n            with gr.Column(scale=0.15, min_width=0):\n                clear = gr.Button(\"Clear\")\n            with gr.Column(scale=0.15, min_width=0):\n                btn = gr.UploadButton(label=\"🖼️\",file_types=[\"image\"])\n\n        lang.change(bot.init_agent, [lang], [input_raws, lang, txt, clear])\n        txt.submit(bot.run_text, [txt, state], [chatbot, state])\n        txt.submit(lambda: \"\", None, txt)\n        btn.upload(bot.run_image, [btn, state, txt, lang], [chatbot, state, txt])\n        clear.click(bot.memory.clear)\n        clear.click(lambda: [], None, chatbot)\n        clear.click(lambda: [], None, state)\n    demo.launch(server_name=\"0.0.0.0\", server_port=7861)\n"
  }
]