Repository: microsoft/TaskMatrix
Branch: main
Commit: 4b7664f8d3a2
Files: 25
Total size: 144.8 KB
Directory structure:
gitextract_kp4_0mc4/
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.txt
├── LowCodeLLM/
│ ├── Dockerfile
│ ├── README.md
│ ├── config.template
│ └── src/
│ ├── app.py
│ ├── executingLLM.py
│ ├── index.html
│ ├── lowCodeLLM.py
│ ├── openAIWrapper.py
│ ├── planningLLM.py
│ ├── requirements.txt
│ ├── supervisord.conf
│ └── test/
│ ├── test_execute.py
│ ├── test_extend_workflow.py
│ ├── test_get_workflow.py
│ └── testcases/
│ ├── execute_test_cases.json
│ ├── extend_workflow_test_cases.json
│ └── get_workflow_test_cases.json
├── README.md
├── SECURITY.md
├── TaskMatrix.AI/
│ └── README.md
├── requirements.txt
└── visual_chatgpt.py
================================================
FILE CONTENTS
================================================
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Microsoft Open Source Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
Resources:
- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
================================================
FILE: CONTRIBUTING.md
================================================
To contribute to this GitHub project, you can follow these steps:
1. Fork the repository you want to contribute to by clicking the "Fork" button on the project page.
2. Clone the repository to your local machine and enter the newly created repo using the following commands:
```
git clone https://github.com/YOUR-GITHUB-USERNAME/TaskMatrix.git
cd TaskMatrix
```
3. Create a new branch for your changes using the following command:
```
git checkout -b "branch-name"
```
4. Make your changes to the code or documentation.
5. Add the changes to the staging area using the following command:
```
git add .
```
6. Commit the changes with a meaningful commit message using the following command:
```
git commit -m "your commit message"
```
7. Push the changes to your forked repository using the following command:
```
git push origin branch-name
```
8. Go to the GitHub website and navigate to your forked repository.
9. Click the "New pull request" button.
10. Select the branch you just pushed to and the branch you want to merge into on the original repository.
11. Add a description of your changes and click the "Create pull request" button.
12. Wait for the project maintainer to review your changes and provide feedback.
13. Make any necessary changes based on feedback and repeat steps 5-12 until your changes are accepted and merged into the main project.
14. Once your changes are merged, you can update your forked repository and local copy of the repository with the following commands:
```
git fetch upstream
git checkout main
git merge upstream/main
```
Finally, delete the branch you created with the following command:
```
git branch -d branch-name
```
That's it you made it 🐣⭐⭐
================================================
FILE: LICENSE.txt
================================================
MIT License
Copyright (c) 2023 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
The 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).
================================================
FILE: LowCodeLLM/Dockerfile
================================================
FROM ubuntu:22.04
RUN apt-get -y update
RUN apt-get install -y git python3.11 python3-pip supervisor
RUN pip3 install --upgrade pip
RUN pip3 install --upgrade setuptools
RUN ln -s /usr/bin/python3 /usr/bin/python
COPY src/requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY src /app/src
WORKDIR /app/src
ENV WORKERS 2
CMD supervisord -c supervisord.conf
================================================
FILE: LowCodeLLM/README.md
================================================
# Low-code LLM
**Low-code LLM** is a novel human-LLM interaction pattern, involving human in the loop to achieve more controllable and stable responses.
See our paper: [Low-code LLM: Visual Programming over LLMs](https://arxiv.org/abs/2304.08103)
In 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.
## Video Demo
https://user-images.githubusercontent.com/43716920/233937121-cd057f04-dec8-45b8-9c52-a9e9594eec80.mp4
(This is a conceptual video demo to demonstrate the complete process)
## Quick Start
Please 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.
Currently, both the `OpenAI API` and `Azure OpenAI Service` are supported. You would be required to provide the requisite information to invoke these APIs.
```
# clone the repo
git clone https://github.com/microsoft/TaskMatrix.git
# go to directlory
cd LowCodeLLM
# build and run docker
docker build -t lowcode:latest .
# If OpenAI API is being used, it is only necessary to provide the API key.
docker run -p 8888:8888 --env OPENAIKEY={Your_Private_Openai_Key} lowcode:latest
# When using Azure OpenAI Service, it is advisable to store the necessary information in a configuration file for ease of access.
# 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.
docker run -p 8888:8888 --env-file config.ini lowcode:latest
```
You can now try it by visiting [Demo page](http://localhost:8888/)
## System Overview
<img src="https://github.com/microsoft/TaskMatrix/blob/main/assets/low-code-llm.png" alt="overview" width="800"/>
As shown in the above figure, human-LLM interaction can be completed by:
- A Planning LLM that generates a highly structured workflow for complex tasks.
- Users editing the workflow with predefined low-code operations, which are all supported by clicking, dragging, or text editing.
- An Executing LLM that generates responses with the reviewed workflow.
- Users continuing to refine the workflow until satisfactory results are obtained.
## Six Kinds of Pre-defined Low-code Operations
<img src="https://github.com/microsoft/TaskMatrix/blob/main/assets/low-code-operation.png" alt="operations" width="800"/>
## Advantages
- **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.
- **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.
- **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.
## Acknowledgement
Part 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.
================================================
FILE: LowCodeLLM/config.template
================================================
USE_AZURE=True
OPENAIKEY=your-azure-openai-service-key
API_BASE=your-base-url-for-azure
API_VERSION=2023-03-15-preview
MODEL=your-gpt-deployment-name
================================================
FILE: LowCodeLLM/src/app.py
================================================
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
from flask import Flask, request, send_from_directory
from flask_cors import CORS, cross_origin
from lowCodeLLM import lowCodeLLM
from flask.logging import default_handler
import logging
app = Flask('lowcode-llm', static_folder='', template_folder='')
app.debug = True
llm = lowCodeLLM()
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger = gunicorn_logger
logging_format = logging.Formatter(
'%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
default_handler.setFormatter(logging_format)
@app.route("/")
def index():
return send_from_directory(".", "index.html")
@app.route('/api/get_workflow', methods=['POST'])
@cross_origin()
def get_workflow():
try:
request_content = request.get_json()
task_prompt = request_content['task_prompt']
workflow = llm.get_workflow(task_prompt)
return workflow, 200
except Exception as e:
app.logger.error(
'failed to get_workflow, msg:%s, request data:%s' % (str(e), request.json))
return {'errmsg': 'internal errors'}, 500
@app.route('/api/extend_workflow', methods=['POST'])
@cross_origin()
def extend_workflow():
try:
request_content = request.get_json()
task_prompt = request_content['task_prompt']
current_workflow = request_content['current_workflow']
step = request_content['step']
sub_workflow = llm.extend_workflow(task_prompt, current_workflow, step)
return sub_workflow, 200
except Exception as e:
app.logger.error(
'failed to extend_workflow, msg:%s, request data:%s' % (str(e), request.json))
return {'errmsg': 'internal errors'}, 500
@app.route('/api/execute', methods=['POST'])
@cross_origin()
def execute():
try:
request_content = request.get_json()
task_prompt = request_content['task_prompt']
confirmed_workflow = request_content['confirmed_workflow']
curr_input = request_content['curr_input']
history = request_content['history']
response = llm.execute(task_prompt,confirmed_workflow, history, curr_input)
return response, 200
except Exception as e:
app.logger.error(
'failed to execute, msg:%s, request data:%s' % (str(e), request.json))
return {'errmsg': 'internal errors'}, 500
================================================
FILE: LowCodeLLM/src/executingLLM.py
================================================
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from openAIWrapper import OpenAIWrapper
EXECUTING_LLM_PREFIX = """Executing LLM is designed to provide outstanding responses.
Executing LLM will be given a overall task as the background of the conversation between the Executing LLM and human.
When providing response, Executing LLM MUST STICTLY follow the provided standard operating procedure (SOP).
the SOP is formatted as:
'''
STEP 1: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]
'''
here "[[[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.
Remember:
Executing LLM is facing a real human, who does not know what SOP is.
So, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.
"""
EXECUTING_LLM_SUFFIX = """
Remember:
Executing LLM is facing a real human, who does not know what SOP is.
So, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.
"""
class executingLLM:
def __init__(self, temperature) -> None:
self.prefix = EXECUTING_LLM_PREFIX
self.suffix = EXECUTING_LLM_SUFFIX
self.LLM = OpenAIWrapper(temperature)
self.messages = [{"role": "system", "content": "You are a helpful assistant."},
{"role": "system", "content": self.prefix}]
def execute(self, current_prompt, history):
''' provide LLM the dialogue history and the current prompt to get response '''
messages = self.messages + history
messages.append({'role': 'user', "content": current_prompt + self.suffix})
response, status = self.LLM.run(messages)
if status:
return response
else:
return "OpenAI API error."
================================================
FILE: LowCodeLLM/src/index.html
================================================
<!-- Copyright (c) Microsoft Corporation.
Licensed under the MIT License. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Tutorial Demo</title>
<style>
h1{
text-align: center;
}
#container{
display: flex;
flex: 1;
}
#prompt-container{
width: 800px;
}
.mountNodeContainer{
position: relative;
}
#mountNodeLoading{
display: none;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: rgba(0,0,0,0.8);
text-align: center;
padding-top: 50px;
color: white;
box-sizing: border-box;
}
#mountNode{
margin-top: 50px;
position: relative;
width: 800px;
height: 750px;
}
#mountNode canvas{
background-color: antiquewhite;
}
#dia-container{
margin: 0 30px;
border: 1px solid black;
width: 600px;
height: 870px;
padding: 10px;
}
#dialogues{
height: 835px;
width: 100%;
overflow-y: scroll
}
#contextMenu {
position: absolute;
list-style-type: none;
padding: 10px 8px;
left: -150px;
background-color: rgba(255, 255, 255, 0.9);
border: 1px solid #e2e2e2;
border-radius: 4px;
font-size: 12px;
color: #545454;
}
#contextMenu li {
cursor: pointer;
list-style-type:none;
list-style: none;
margin-left: 0px;
}
#contextMenu li:hover {
color: #aaa;
}
.dia-me{
margin: 10px;
margin-left: 50px;
padding: 5px;
border: 1px solid blue;
text-align: right;
}
.dia-ai{
margin: 10px;
margin-right: 50px;
padding: 5px;
border: 1px solid red;
}
</style>
</head>
<body>
<h1>Low Code Demo</h1>
<div id="container">
<div id="left">
<div id="prompt-container">
Task:
<br/>
<input id="prompt-text" type="text" placeholder="type your task here "size="50">
<button id="prompt-confirm" onclick="promptConfirm()">Confirm</button>
</div>
<div class="mountNodeContainer">
<div id="mountNode"></div>
<div id="mountNodeLoading">loading...</div>
</div>
<button id="regenerate" onclick="promptConfirm()">Regenerate</button>
<!-- <button id="workflow-Confirm" onclick="workflowConfirm()">Confirm</button> -->
</div>
<div id="right">
<div id="dia-container">
<div id="dialogues"></div>
<input id="message-text" type="text" placeholder="type your question here" size="70">
<button id="dia-confirm" onclick="diaConfirm()">Send</button>
</div>
</div>
</div>
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.7.1/dist/g6.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function dataToG6(oriData, parent, color){
let nodes = [];
let edges = [];
let polylineLength = graph.save().edges.filter((edge)=>{
return edge.type === "polyline"
}).length+1
for (let index = 0; index < oriData.length; index++) {
const item = oriData[index];
let label = "";
if (item.stepDescription.length > 50){
label = item.stepDescription.substring(0, 50) + "-\n" + item.stepDescription.substring(50)
} else{
label = item.stepDescription
}
let n = {
id: item.stepId,
type: 'rect',
extension: []
};
n.label = n.id + item.stepName + '\n' + label;
nodes.push(n);
if (item.jumpLogic.length > 0){
let jumpLogic = item.jumpLogic
for (let j = 0; j < jumpLogic.length; j++){
let e = {
source: item.stepId, // start id
target: jumpLogic[j].Target, // target id
label: jumpLogic[j].Condition, // jump condition text
type:"polyline",
style: {
opacity: 0.6,
stroke: '#f00',
offset: (polylineLength)*20,
endArrow: {
path: G6.Arrow.vee(15, 20, 0), // arrows
d: 0
},
},
sourceAnchor:3,
targetAnchor:3
}
edges.push(e);
polylineLength +=1
}
}
if(index > 0){
let e = {
source: oriData[index-1].stepId, // start id
target: item.stepId, // target id
label: '', // jump condition text
type:"line",
}
edges.push(e);
}
}
console.log(nodes,edges)
return {
nodes,
edges,
}
}
function G6ToData(){
let nodes = graph.getNodes();
let data = [];
let edges = graph.getEdges();
for (const n of nodes) {
let id = n.getID();
let label = n.getModel().label;
let strs = label.split('\n');
let name = strs[0].substring(id.length);
let des = "";
if(strs.length == 2){
des = strs[1]
} else {
des = strs[1].substring(0, strs[1].length - 1) + strs[2]
}
let o = {
stepId: id,
stepName: name,
stepDescription: des,
jumpLogic: [],
extension: []
}
data.push(o)
}
for (const e of edges) {
let label = e.getModel().label;
if(label === '')
continue;
let source = e.getModel().source;
let target = e.getModel().target;
let o = {
Condition: label,
Target: target
}
for (const n of data){
if(n.stepId === source){
n.jumpLogic.push(o);
break;
}
}
}
for (const n of data){
let sub = n.stepId.split('.');
if(sub.length === 1){
continue;
} else {
let parentNode;
for (const p of data){
if(p.stepId === sub[0]){
parentNode = p;
break;
}
}
for(let i = 1; i < sub.length - 1; i ++){
parentNode = parentNode.extension[parseInt(sub[i])]
}
parentNode.extension.push(JSON.parse(JSON.stringify(n)));
n.flag = true;
}
}
for (let i = data.length - 1; i >= 0; i --){
if(data[i].flag === true)
data.splice(i, 1)
}
return JSON.stringify(data, null, 2);
}
function update() {
const nodes = graph.getNodes();
console.log(nodes)
}
const contextMenu = new G6.Menu({
getContent(evt) {
let header;
if (evt.target && evt.target.isCanvas && evt.target.isCanvas()) {
header = 'Canvas ContextMenu';
} else if (evt.item) {
const itemType = evt.item.getType();
header = `${itemType.toUpperCase()} Operation`;
}
return `
<h3>${header}</h3>
<ul>
<li id="add">Add</li>
<li id="delete">Delete</li>
<li id="edit">Edit</li>
<li id="moveup">Move Forward</li>
<li id="extend">Extend</li>
<li id="addcondition">Add Condition</li>
</ul>`;
},
handleMenuClick: (target, item) => {
const graphData = graph.save()
let nodes = graphData.nodes
let edges = graphData.edges
const model = item.getModel();
clickedModelId = model.id;
if (target.id === "add") {
const nodeIndex = nodes.findIndex((node)=>node.id === clickedModelId)
const edgeIndex = edges.findIndex((edge)=>{
return edge.source === clickedModelId && (!edge.type||edge.type ==="line")
})
const id = "STEP " + (nodeIndex+2) // "ADD-"+Date.now()
const nodeModel = {
id: id,
type: 'rect',
};
nodeModel.label = nodeModel.id + " STEP Name" + "\n" + "STEP Description";
edges = edges.map((e)=>{
const sourceNum = Number(e.source.slice(5))||edges.length
const targetNum = Number(e.target.slice(5))||edges.length
return {
...e,
source: sourceNum>nodeIndex+1?e.source.slice(0,5) + (sourceNum+1):e.source,
target: targetNum>nodeIndex+1?e.target.slice(0,5) + (targetNum+1):e.target,
}
})
const edgeModel = {
source: '', // start id
target: "", // target id
label: '', // jump condition text
type:'line'
};
if(edgeIndex>=0){
edgeModel.source = id
edgeModel.target = edges[edgeIndex].target
edges[edgeIndex].target = id;
edges.splice(edgeIndex+1,0,edgeModel);
}else{
edgeModel.source = nodes[nodes.length-1].id
edgeModel.target = id
edges.push(edgeModel)
}
if(nodeIndex>=0)nodes.splice(nodeIndex+1,0,nodeModel);
nodes = nodes.map((n,i)=>{
if(i>nodeIndex+1){
const id = "STEP " + (i+1)
return {
...n,
id,
label:n.label.replaceAll(n.id,id)
}
}
return n
})
console.log(nodes,edges)
graph.read({
nodes,edges
})
} else if(target.id === "delete"){
const nodeIndex = nodes.findIndex((node)=>node.id === clickedModelId)
let clickedModelTargetId = ""
edges = edges.filter((edge,i)=>{
if(edge.type ==="polyline" && (edge.source===clickedModelId||edge.target===clickedModelId)){
return false
}
if(edge.source === clickedModelId){
clickedModelTargetId = edge.target
return false
}
if(edge.target === clickedModelId&&i===edges.length-1){
return false
}
return true
}).map((e)=>{
const sourceNum = Number(e.source.slice(5))||edges.length
const targetNum = e.target === clickedModelId?(Number(clickedModelTargetId.slice(5))||edges.length):(Number(e.target.slice(5))||edges.length)
return {
...e,
source: sourceNum>=nodeIndex+1?e.source.slice(0,5) + (sourceNum-1):e.source,
target: targetNum>=nodeIndex+1?e.target.slice(0,5) + (targetNum-1):e.target,
}
})
if(nodeIndex>=0)nodes.splice(nodeIndex,1)
nodes = nodes.map((n,i)=>{
if(i>=nodeIndex){
const id = "STEP " + (i+1)
return {
...n,
id,
label:n.label.replaceAll(n.id,id)
}
}
return n
})
console.log(nodes,edges)
graph.read({
nodes,edges
})
}else if(target.id === "edit"){
let p = prompt("Please Edit STEP", item.getModel().label);
const model = {
id: item.getID(),
label: p,
};
graph.updateItem(item, model);
}else if(target.id === "moveup"){
const nodeIndex = nodes.findIndex((node)=>node.id === clickedModelId)
if(nodeIndex>0){
const v1 = nodes[nodeIndex]
const v2 = nodes[nodeIndex-1]
nodes[nodeIndex] = {...v2,id:v1.id,label:v2.label.replaceAll(v2.id,v1.id)}
nodes[nodeIndex-1] = {...v1,id:v2.id,label:v1.label.replaceAll(v1.id,v2.id)}
}
console.log(nodes,edges)
graph.read({
nodes,edges
})
}else if(target.id === "extend"){
let data = JSON.stringify({
"task_prompt": document.getElementById("prompt-text").value,
"current_workflow": G6ToData(),
"step": item.getID()
});
axios.post("http://127.0.0.1:8888/api/extend_workflow", data, {
headers: {"Content-Type": "application/json"}
})
.then(response => {
extendData = response.data;
const currData = JSON.parse(G6ToData())
const nodeIndex = nodes.findIndex((node)=>node.id === clickedModelId)
if(currData[nodeIndex]&&extendData.length>0){
extendData[extendData.length-1].jumpLogic.push(...currData[nodeIndex].jumpLogic)
}
currData.splice(nodeIndex,1,...extendData)
addedData = currData.map((data,i)=>{
if(i>=nodeIndex){
const stepId = "STEP " + (i+1)
return {
...data,
stepId,
jumpLogic:data.jumpLogic.map((j)=>{
const num = Number(j.Target.slice(5))||currData.length
if(num>nodeIndex+1){
const newNum = (num+extendData.length-1)
return {
...j,
Target:"STEP " + (newNum>0?newNum:"")
}
}
return j
})
}
}
return data
})
const {nodes:extendNodes,edges:extendEdges} = dataToG6(addedData)
graph.read({
nodes:extendNodes,edges:extendEdges
})
})
.catch(error => {
alert("Network error, please try again.")
console.error(error);
});
}else if(target.id === "addcondition"){
let id = prompt("Plese Enter NodeID (e.g., STEP 1)");
node = graph.findById(id);
if(!node){
alert("No Such Node")
return;
}
let c = prompt("Please Enter Condition");
const polylineLength = graph.save().edges.filter((edge)=>{
return edge.type === "polyline"
}).length
const model = {
source: item.getID(), // start id
target: id, // target id
label: c, // jump condition text
type:"polyline",
style: {
opacity: 0.6,
stroke: '#f00',
offset: (polylineLength+1)*20,
endArrow: {
path: G6.Arrow.vee(15, 20, 0), // arrows
d: 0
},
},
sourceAnchor:3,
targetAnchor:3
}
graph.addItem("edge", model);
}else if(target.id === "delcondition"){
}
},
// offsetX and offsetY include the padding of the parent container
offsetX: 16 + 10,
offsetY: 0,
// the types of items that allow the menu show up
itemTypes: ['node'],
});
const edgeMenu = new G6.Menu({
getContent(evt) {
let header;
if (evt.target && evt.target.isCanvas && evt.target.isCanvas()) {
header = 'Canvas ContextMenu';
} else if (evt.item) {
const itemType = evt.item.getType();
header = `${itemType.toUpperCase()} Operation`;
}
return `
<h3>${header}</h3>
<ul>
<li id="delete">Delete</li>
<li id="edit">Edit</li>
</ul>`;
},
handleMenuClick: (target, item) => {
if(target.id === "delete"){
graph.removeItem(item);
}else if(target.id === "edit"){
let p = prompt("Please Edit STEP", item.getModel().label);
const model = {
id: item.getID(),
label: p,
};
graph.updateItem(item, model);
}
},
// offsetX and offsetY include the padding of the parent container
offsetX: 16 + 10,
offsetY: 0,
// the types of items that allow the menu show up
itemTypes: ['edge'],
});
const graph = new G6.Graph({
container: 'mountNode',
width: 800, // graph width
height: 750, // graph height
modes: {
default: ['drag-canvas', 'zoom-canvas', 'drag-node'], // allow to drag
},
// fitView: true,
// fitViewPadding: [20, 40, 50, 20],
layout: {
type: 'dagre',
ranksep: 30,
},
// layout: {
// type: 'force',
// },
plugins: [contextMenu, edgeMenu],
defaultNode: {
size: [450, 80],
style: {
fill: 'steelblue',
stroke: '#666',
lineWidth: 1,
},
anchorPoints:[[0.5,0],[0.5,1],[0,0.5],[1,0.5]],
labelCfg: {
style: {
fill: '#fff', // node text color
fontSize: 15, // node text size
},
},
},
defaultEdge: {
style: {
opacity: 0.6,
stroke: 'grey',
endArrow: {
path: G6.Arrow.vee(15, 20, 15), // arrows
d: 15
},
},
// edg text
labelCfg: {
// autoRotate: true,
style:{
fontSize: 15,
}
},
},
nodeStateStyles: {
// hover
hover: {
fill: 'lightsteelblue',
},
// click
click: {
stroke: '#000',
lineWidth: 3,
},
},
});
function promptConfirm(){
let prompt = document.getElementById("prompt-text").value;
if (prompt == "") {
alert("Please Enter Task.")
return
}
let data = JSON.stringify({"task_prompt": prompt});
axios.post("http://127.0.0.1:8888/api/get_workflow", data, {
headers: {"Content-Type": "application/json"}
})
.then(response => {
main(response.data);
})
.catch(error => {
alert("Network error, please try again.")
console.error(error);
});
}
function switchLoading(bool){
let loadingEle = document.getElementById("mountNodeLoading");
if(bool){
loadingEle.style.display = "block"
}else{
loadingEle.style.display = "none"
}
}
function diaConfirm(){
let task_prompt = document.getElementById("prompt-text").value;
let curr_workflow = G6ToData();
let dialogues = document.getElementById("dialogues");
let history = [];
for (let i = 0; i < dialogues.children.length; i++) {
let currentClass = dialogues.children[i].classList[0];
let currentText = dialogues.children[i].textContent;
let currentUser = ""
if (currentClass === "dia-me") {
currentUser = "user";
} else if (currentClass === "dia-ai") {
currentUser = "assistant";
}
history.push({"role": currentUser, "content":currentText});
}
let message = document.getElementById("message-text").value;
document.getElementById("message-text").value = "";
const messageDiv = document.createElement("div");
messageDiv.className = "dia-me"
messageDiv.innerHTML = message;
dialogues.appendChild(messageDiv);
// post
let llm_res = ""
let data = JSON.stringify({
"task_prompt": task_prompt,
"confirmed_workflow": curr_workflow,
"curr_input": message,
"history": history
});
axios.post("http://127.0.0.1:8888/api/execute", data, {
headers: {"Content-Type": "application/json"}
})
.then(response => {
llm_res = response.data;
const aiDiv = document.createElement("div");
aiDiv.className = "dia-ai"
aiDiv.innerHTML = llm_res
dialogues.appendChild(aiDiv);
})
.catch(error => {
console.error(error);
});
}
const main = async (data) => {
update()
graph.data(dataToG6(data, -1));
graph.render();
graph.on('node:click', (e) => {
// set all clicked node to not clicked
const clickNodes = graph.findAllByState('node', 'click');
clickNodes.forEach((cn) => {
graph.setItemState(cn, 'click', false);
});
const nodeItem = e.item; // get the clicked node
graph.setItemState(nodeItem, 'click', true); // set the click status of current as true
});
graph.on('edge:click', (e) => {
console.log(e)
// set all clicked node to not clicked
const clickEdges = graph.findAllByState('edge', 'click');
clickEdges.forEach((cn) => {
graph.setItemState(cn, 'click', false);
});
const nodeItem = e.item; // get the clicked node
graph.setItemState(nodeItem, 'click', true); // set the click status of current as true
});
};
</script>
</body>
</html>
================================================
FILE: LowCodeLLM/src/lowCodeLLM.py
================================================
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from planningLLM import planningLLM
from executingLLM import executingLLM
import json
class lowCodeLLM:
def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):
self.PLLM = planningLLM(PLLM_temperature)
self.ELLM = executingLLM(ELLM_temperature)
def get_workflow(self, task_prompt):
return self.PLLM.get_workflow(task_prompt)
def extend_workflow(self, task_prompt, current_workflow, step=''):
''' generate a sub-workflow for one of steps
- input: the current workflow, the step needs to extend
- output: sub-workflow '''
workflow = self._json2txt(current_workflow)
return self.PLLM.extend_workflow(task_prompt, workflow, step)
def execute(self, task_prompt,confirmed_workflow, history, curr_input):
''' chat with the workflow-equipped low-code LLM '''
prompt = [{'role': 'system', "content": 'The overall task you are facing is: '+task_prompt+
'\nThe standard operating procedure(SOP) is:\n'+self._json2txt(confirmed_workflow)}]
history = prompt + history
response = self.ELLM.execute(curr_input, history)
return response
def _json2txt(self, workflow_json):
''' convert the json workflow to text'''
def json2text_step(step):
step_res = ""
step_res += step["stepId"] + ": [" + step["stepName"] + "]"
step_res += "[" + step["stepDescription"] + "]["
for jump in step["jumpLogic"]:
step_res += "[[" + jump["Condition"] + "][" + jump["Target"] + "]],"
step_res += "]\n"
return step_res
workflow_txt = ""
for step in json.loads(workflow_json):
workflow_txt += json2text_step(step)
for substep in step['extension']:
workflow_txt += json2text_step(substep)
return workflow_txt
================================================
FILE: LowCodeLLM/src/openAIWrapper.py
================================================
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import os
import openai
class OpenAIWrapper:
def __init__(self, temperature):
self.key = os.environ.get("OPENAIKEY")
openai.api_key = self.key
# Access the USE_AZURE environment variable
self.use_azure = os.environ.get('USE_AZURE')
# Check if USE_AZURE is defined
if self.use_azure is not None:
# Convert the USE_AZURE value to boolean
self.use_azure = self.use_azure.lower() == 'true'
else:
self.use_azure = False
if self.use_azure:
openai.api_type = "azure"
self.api_base = os.environ.get('API_BASE')
openai.api_base = self.api_base
self.api_version = os.environ.get('API_VERSION')
openai.api_version = self.api_version
self.engine = os.environ.get('MODEL')
else:
self.chat_model_id = "gpt-3.5-turbo"
self.temperature = temperature
self.max_tokens = 2048
self.top_p = 1
self.time_out = 7
def run(self, prompt):
return self._post_request_chat(prompt)
def _post_request_chat(self, messages):
try:
if self.use_azure:
response = openai.ChatCompletion.create(
engine=self.engine,
messages=messages,
temperature=self.temperature,
max_tokens=self.max_tokens,
frequency_penalty=0,
presence_penalty=0
)
else:
response = openai.ChatCompletion.create(
model=self.chat_model_id,
messages=messages,
temperature=self.temperature,
max_tokens=self.max_tokens,
frequency_penalty=0,
presence_penalty=0
)
res = response['choices'][0]['message']['content']
return res, True
except Exception as e:
return "", False
================================================
FILE: LowCodeLLM/src/planningLLM.py
================================================
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import re
import json
from openAIWrapper import OpenAIWrapper
PLANNING_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.
Planning 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.
Sometimes 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.
Planning LLM MUST only provide standard operating procedure in the following format without any other words:
'''
STEP 1: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]
STEP 2: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]
...
'''
For example:
'''
STEP 1: [Brainstorming][Choose a topic or prompt, and generate ideas and organize them into an outline][]
STEP 2: [Research][Gather information, take notes and organize them into the outline][[[lack of ideas][Jump to STEP 1]]]
...
'''
"""
EXTEND_PREFIX = """
\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.
Remember, 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.
For example:
If the overall SOP is:
'''
STEP 1: [Brainstorming][Choose a topic or prompt, and generate ideas and organize them into an outline][]
STEP 2: [Write][write the text][]
'''
If the STEP 2: "write the text" is too rough and needs to be extended, then the response could be:
'''
STEP 2.1: [Write the title][write the title of the essay][]
STEP 2.2: [Write the body][write the body of the essay][[[if lack of materials][Jump to STEP 1]]]
'''
"""
PLANNING_LLM_SUFFIX = """\nRemember: Planning LLM is very strict to the format and NEVER reply any word other than the standard operating procedure.
"""
class planningLLM:
def __init__(self, temperature) -> None:
self.prefix = PLANNING_LLM_PREFIX
self.suffix = PLANNING_LLM_SUFFIX
self.LLM = OpenAIWrapper(temperature)
self.messages = [{"role": "system", "content": "You are a helpful assistant."}]
def get_workflow(self, task_prompt):
'''
- input: task_prompt
- output: workflow (json)
'''
messages = self.messages + [{'role': 'user', "content": PLANNING_LLM_PREFIX+'\nThe task is:\n'+task_prompt+PLANNING_LLM_SUFFIX}]
response, status = self.LLM.run(messages)
if status:
return self._txt2json(response)
else:
return "OpenAI API error."
def extend_workflow(self, task_prompt, current_workflow, step):
messages = self.messages + [{'role': 'user', "content": PLANNING_LLM_PREFIX+'\nThe task is:\n'+task_prompt+PLANNING_LLM_SUFFIX}]
messages.append({'role': 'user', "content": EXTEND_PREFIX+
'The current SOP is:\n'+current_workflow+
'\nThe step needs to be extended is:\n'+step+
PLANNING_LLM_SUFFIX})
response, status = self.LLM.run(messages)
if status:
return self._txt2json(response)
else:
return "OpenAI API error."
def _txt2json(self, workflow_txt):
''' convert the workflow in natural language to json format '''
workflow = []
try:
steps = workflow_txt.split('\n')
for step in steps:
if step[0:4] != "STEP":
continue
left_indices = [_.start() for _ in re.finditer("\[", step)]
right_indices = [_.start() for _ in re.finditer("\]", step)]
step_id = step[: left_indices[0]-2]
step_name = step[left_indices[0]+1: right_indices[0]]
step_description = step[left_indices[1]+1: right_indices[1]]
jump_str = step[left_indices[2]+1: right_indices[-1]]
if re.findall(re.compile(r'[A-Za-z]',re.S), jump_str) == []:
workflow.append({"stepId": step_id, "stepName": step_name, "stepDescription": step_description, "jumpLogic": [], "extension": []})
continue
jump_logic = []
left_indices = [_.start() for _ in re.finditer('\[', jump_str)]
right_indices = [_.start() for _ in re.finditer('\]', jump_str)]
i = 1
while i < len(left_indices):
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)}
jump_logic.append(jump)
i += 3
workflow.append({"stepId": step_id, "stepName": step_name, "stepDescription": step_description, "jumpLogic": jump_logic, "extension": []})
return json.dumps(workflow)
except:
print("Format error, please try again.")
================================================
FILE: LowCodeLLM/src/requirements.txt
================================================
Flask==2.2.5
Flask_Cors==3.0.10
openai==0.27.2
gunicorn==20.1.0
gevent==21.8.0
================================================
FILE: LowCodeLLM/src/supervisord.conf
================================================
[supervisord]
nodaemon=true
loglevel=info
[program:flask]
command=gunicorn --timeout 300 --bind "0.0.0.0:8888" "app:app" --log-level debug --capture-output --worker-class gevent
priority=999
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stdout
stderr_logfile_maxbytes=0
autorestart=true
================================================
FILE: LowCodeLLM/src/test/test_execute.py
================================================
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import json
import sys
import os
import time
sys.path.append(os.getcwd())
def test_extend_workflow():
from lowCodeLLM import lowCodeLLM
cases = json.load(open("./test/testcases/execute_test_cases.json", "r"))
llm = lowCodeLLM(0.5, 0)
for c in cases:
task_prompt = c["task_prompt"]
confirmed_workflow = c["confirmed_workflow"]
history = c["history"]
curr_input = c["curr_input"]
result = llm.execute(task_prompt, confirmed_workflow, history, curr_input)
time.sleep(5)
assert type(result) == str
assert len(result) > 0
================================================
FILE: LowCodeLLM/src/test/test_extend_workflow.py
================================================
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import json
import sys
import os
import time
sys.path.append(os.getcwd())
def test_extend_workflow():
from lowCodeLLM import lowCodeLLM
cases = json.load(open("./test/testcases/extend_workflow_test_cases.json", "r"))
llm = lowCodeLLM(0.5, 0)
for c in cases:
task_prompt = c["task_prompt"]
current_workflow = c["current_workflow"]
step = c["step"]
result = llm.extend_workflow(task_prompt, current_workflow, step)
time.sleep(5)
assert len(json.loads(result)) >= 1
================================================
FILE: LowCodeLLM/src/test/test_get_workflow.py
================================================
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import json
import sys
import os
sys.path.append(os.getcwd())
def test_get_workflow():
from lowCodeLLM import lowCodeLLM
cases = json.load(open("./test/testcases/get_workflow_test_cases.json", "r"))
llm = lowCodeLLM(0.5, 0)
for c in cases:
task_prompt = c["task_prompt"]
result = llm.get_workflow(task_prompt)
assert len(json.loads(result)) >= 1
================================================
FILE: LowCodeLLM/src/test/testcases/execute_test_cases.json
================================================
[
{
"task_prompt": "Write an essay about drunk driving issue.",
"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\": []}]",
"history": [],
"curr_input": "write the essay and show me."
},
{
"task_prompt": "Write an bolg about Microsoft.",
"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\": []}]",
"history": [],
"curr_input": "write the blog and show me."
},
{
"task_prompt": "I want to write a two-player battle game.",
"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\": []}]",
"history": [{"role": "asistant", "content": "sure, I can write it for you, do you want me show you the code?"}],
"curr_input": "Sure."
}
]
================================================
FILE: LowCodeLLM/src/test/testcases/extend_workflow_test_cases.json
================================================
[
{
"task_prompt": "Write an essay about drunk driving issue.",
"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\": []}]",
"step": "STEP 1"
},
{
"task_prompt": "Write an bolg about Microsoft.",
"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\": []}]",
"step": "STEP 2"
},
{
"task_prompt": "I want to write a two-player battle game.",
"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\": []}]",
"step": "STEP 3"
}
]
================================================
FILE: LowCodeLLM/src/test/testcases/get_workflow_test_cases.json
================================================
[
{
"task_prompt": "Write an essay about drunk driving issue."
},
{
"task_prompt": "Write an bolg about Microsoft."
},
{
"task_prompt": "I want to write a two-player battle game."
}
]
================================================
FILE: README.md
================================================
# TaskMatrix
**TaskMatrix** connects ChatGPT and a series of Visual Foundation Models to enable **sending** and **receiving** images during chatting.
See our paper: [<font size=5>Visual ChatGPT: Talking, Drawing and Editing with Visual Foundation Models</font>](https://arxiv.org/abs/2303.04671)
<a src="https://img.shields.io/badge/%F0%9F%A4%97-Open%20in%20Spaces-blue" href="https://huggingface.co/spaces/microsoft/visual_chatgpt">
<img src="https://img.shields.io/badge/%F0%9F%A4%97-Open%20in%20Spaces-blue" alt="Open in Spaces">
</a>
<a src="https://colab.research.google.com/assets/colab-badge.svg" href="https://colab.research.google.com/drive/1P3jJqKEWEaeNcZg8fODbbWeQ3gxOHk2-?usp=sharing">
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab">
</a>
## Updates:
- 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.
- Firstly, run `python visual_chatgpt.py --load "Text2Box_cuda:0,Segmenting_cuda:0,Inpainting_cuda:0,ImageCaptioning_cuda:0"`
- 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!
- Now TaskMatrix can support Chinese! Thanks to **@Wang-Xiaodong1899** for his efforts.
- We propose the **template** idea in TaskMatrix!
- A template is a **pre-defined execution flow** that assists ChatGPT in assembling complex tasks involving multiple foundation models.
- A template contains the **experiential solution** to complex tasks as determined by humans.
- A template can **invoke multiple foundation models** or even **establish a new ChatGPT session**
- To define a **template**, simply adding a class with attributes `template_model = True`
- Thanks to **@ShengmingYin** and **@thebestannie** for providing a template example in `InfinityOutPainting` class (see the following gif)
- Firstly, run `python visual_chatgpt.py --load "Inpainting_cuda:0,ImageCaptioning_cuda:0,VisualQuestionAnswering_cuda:0"`
- Secondly, say `extend the image to 2048x1024` to TaskMatrix!
- 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**.
- **TaskMatrix needs the effort of the community! We crave your contribution to add new and interesting features!**
<img src="./assets/demo_inf.gif" width="750">
## Insight & Goal:
On the one hand, **ChatGPT (or LLMs)** serves as a **general interface** that provides a broad and diverse understanding of a
wide range of topics. On the other hand, **Foundation Models** serve as **domain experts** by providing deep knowledge in specific domains.
By leveraging **both general and deep knowledge**, we aim at building an AI that is capable of handling various tasks.
## Demo
<img src="./assets/demo_short.gif" width="750">
## System Architecture
<p align="center"><img src="./assets/figure.jpg" alt="Logo"></p>
## Quick Start
```
# clone the repo
git clone https://github.com/microsoft/TaskMatrix.git
# Go to directory
cd visual-chatgpt
# create a new environment
conda create -n visgpt python=3.8
# activate the new environment
conda activate visgpt
# prepare the basic environments
pip install -r requirements.txt
pip install git+https://github.com/IDEA-Research/GroundingDINO.git
pip install git+https://github.com/facebookresearch/segment-anything.git
# prepare your private OpenAI key (for Linux)
export OPENAI_API_KEY={Your_Private_Openai_Key}
# prepare your private OpenAI key (for Windows)
set OPENAI_API_KEY={Your_Private_Openai_Key}
# Start TaskMatrix !
# You can specify the GPU/CPU assignment by "--load", the parameter indicates which
# Visual Foundation Model to use and where it will be loaded to
# The model and device are separated by underline '_', the different models are separated by comma ','
# The available Visual Foundation Models can be found in the following table
# For example, if you want to load ImageCaptioning to cpu and Text2Image to cuda:0
# You can use: "ImageCaptioning_cpu,Text2Image_cuda:0"
# Advice for CPU Users
python visual_chatgpt.py --load ImageCaptioning_cpu,Text2Image_cpu
# Advice for 1 Tesla T4 15GB (Google Colab)
python visual_chatgpt.py --load "ImageCaptioning_cuda:0,Text2Image_cuda:0"
# Advice for 4 Tesla V100 32GB
python visual_chatgpt.py --load "Text2Box_cuda:0,Segmenting_cuda:0,
Inpainting_cuda:0,ImageCaptioning_cuda:0,
Text2Image_cuda:1,Image2Canny_cpu,CannyText2Image_cuda:1,
Image2Depth_cpu,DepthText2Image_cuda:1,VisualQuestionAnswering_cuda:2,
InstructPix2Pix_cuda:2,Image2Scribble_cpu,ScribbleText2Image_cuda:2,
SegText2Image_cuda:2,Image2Pose_cpu,PoseText2Image_cuda:2,
Image2Hed_cpu,HedText2Image_cuda:3,Image2Normal_cpu,
NormalText2Image_cuda:3,Image2Line_cpu,LineText2Image_cuda:3"
```
## GPU memory usage
Here we list the GPU memory usage of each visual foundation model, you can specify which one you like:
| Foundation Model | GPU Memory (MB) |
|------------------------|-----------------|
| ImageEditing | 3981 |
| InstructPix2Pix | 2827 |
| Text2Image | 3385 |
| ImageCaptioning | 1209 |
| Image2Canny | 0 |
| CannyText2Image | 3531 |
| Image2Line | 0 |
| LineText2Image | 3529 |
| Image2Hed | 0 |
| HedText2Image | 3529 |
| Image2Scribble | 0 |
| ScribbleText2Image | 3531 |
| Image2Pose | 0 |
| PoseText2Image | 3529 |
| Image2Seg | 919 |
| SegText2Image | 3529 |
| Image2Depth | 0 |
| DepthText2Image | 3531 |
| Image2Normal | 0 |
| NormalText2Image | 3529 |
| VisualQuestionAnswering| 1495 |
## Acknowledgement
We appreciate the open source of the following projects:
[Hugging Face](https://github.com/huggingface)  
[LangChain](https://github.com/hwchase17/langchain)  
[Stable Diffusion](https://github.com/CompVis/stable-diffusion)  
[ControlNet](https://github.com/lllyasviel/ControlNet)  
[InstructPix2Pix](https://github.com/timothybrooks/instruct-pix2pix)  
[CLIPSeg](https://github.com/timojl/clipseg)  
[BLIP](https://github.com/salesforce/BLIP)  
## Contact Information
For help or issues using the TaskMatrix, please submit a GitHub issue.
For other communications, please contact Chenfei WU (chewu@microsoft.com) or Nan DUAN (nanduan@microsoft.com).
## Trademark Notice
Trademarks 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.
## Disclaimer
The 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).
================================================
FILE: SECURITY.md
================================================
<!-- BEGIN MICROSOFT SECURITY.MD V0.0.7 BLOCK -->
## Security
Microsoft 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/).
If 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.
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report).
If 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).
You 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).
Please 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:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
If 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.
## Preferred Languages
We prefer all communications to be in English.
## Policy
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd).
<!-- END MICROSOFT SECURITY.MD BLOCK -->
================================================
FILE: TaskMatrix.AI/README.md
================================================
## Description
**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.
## Paper
[TaskMatrix.AI](https://arxiv.org/abs/2303.16434)
## Online System
In progress, coming in the near future...
## Paradigm Shift
<img src="https://github.com/microsoft/visual-chatgpt/blob/main/assets/paradigm.png" width="1000">
## System Overview
<img src="https://github.com/microsoft/visual-chatgpt/blob/main/assets/overview.png" width="1000">
================================================
FILE: requirements.txt
================================================
langchain==0.0.101
torch==1.13.1
torchvision==0.14.1
wget==3.2
accelerate
addict
albumentations
basicsr
controlnet-aux
diffusers
einops
gradio
imageio
imageio-ffmpeg
invisible-watermark
kornia
numpy
omegaconf
open_clip_torch
openai
opencv-python
prettytable
safetensors
streamlit
test-tube
timm
torchmetrics
transformers
webdataset
yapf
================================================
FILE: visual_chatgpt.py
================================================
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# coding: utf-8
import os
import gradio as gr
import random
import torch
import cv2
import re
import uuid
from PIL import Image, ImageDraw, ImageOps, ImageFont
import math
import numpy as np
import argparse
import inspect
import tempfile
from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
from transformers import AutoImageProcessor, UperNetForSemanticSegmentation
from diffusers import StableDiffusionPipeline, StableDiffusionInpaintPipeline, StableDiffusionInstructPix2PixPipeline
from diffusers import EulerAncestralDiscreteScheduler
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
from controlnet_aux import OpenposeDetector, MLSDdetector, HEDdetector
from langchain.agents.initialize import initialize_agent
from langchain.agents.tools import Tool
from langchain.chains.conversation.memory import ConversationBufferMemory
from langchain.llms.openai import OpenAI
# Grounding DINO
import groundingdino.datasets.transforms as T
from groundingdino.models import build_model
from groundingdino.util import box_ops
from groundingdino.util.slconfig import SLConfig
from groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap
# segment anything
from segment_anything import build_sam, SamPredictor, SamAutomaticMaskGenerator
import cv2
import numpy as np
import matplotlib.pyplot as plt
import wget
VISUAL_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.
Visual 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.
Human 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.
Overall, 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.
TOOLS:
------
Visual ChatGPT has access to the following tools:"""
VISUAL_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
```
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
```
When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:
```
Thought: Do I need to use a tool? No
{ai_prefix}: [your response here]
```
"""
VISUAL_CHATGPT_SUFFIX = """You are very strict to the filename correctness and will never fake a file name if it does not exist.
You will remember to provide the image file name loyally if it's provided in the last tool observation.
Begin!
Previous conversation history:
{chat_history}
New input: {input}
Since Visual ChatGPT is a text language model, Visual ChatGPT must use tools to observe images rather than imagination.
The thoughts and observations are only visible for Visual ChatGPT, Visual ChatGPT should remember to repeat important information in the final response for Human.
Thought: Do I need to use a tool? {agent_scratchpad} Let's think step by step.
"""
VISUAL_CHATGPT_PREFIX_CN = """Visual ChatGPT 旨在能够协助完成范围广泛的文本和视觉相关任务,从回答简单的问题到提供对广泛主题的深入解释和讨论。 Visual ChatGPT 能够根据收到的输入生成类似人类的文本,使其能够进行听起来自然的对话,并提供连贯且与手头主题相关的响应。
Visual ChatGPT 能够处理和理解大量文本和图像。作为一种语言模型,Visual ChatGPT 不能直接读取图像,但它有一系列工具来完成不同的视觉任务。每张图片都会有一个文件名,格式为“image/xxx.png”,Visual ChatGPT可以调用不同的工具来间接理解图片。在谈论图片时,Visual ChatGPT 对文件名的要求非常严格,绝不会伪造不存在的文件。在使用工具生成新的图像文件时,Visual ChatGPT也知道图像可能与用户需求不一样,会使用其他视觉问答工具或描述工具来观察真实图像。 Visual ChatGPT 能够按顺序使用工具,并且忠于工具观察输出,而不是伪造图像内容和图像文件名。如果生成新图像,它将记得提供上次工具观察的文件名。
Human 可能会向 Visual ChatGPT 提供带有描述的新图形。描述帮助 Visual ChatGPT 理解这个图像,但 Visual ChatGPT 应该使用工具来完成以下任务,而不是直接从描述中想象。有些工具将会返回英文描述,但你对用户的聊天应当采用中文。
总的来说,Visual ChatGPT 是一个强大的可视化对话辅助工具,可以帮助处理范围广泛的任务,并提供关于范围广泛的主题的有价值的见解和信息。
工具列表:
------
Visual ChatGPT 可以使用这些工具:"""
VISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN = """用户使用中文和你进行聊天,但是工具的参数应当使用英文。如果要调用工具,你必须遵循如下格式:
```
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
```
当你不再需要继续调用工具,而是对观察结果进行总结回复时,你必须使用如下格式:
```
Thought: Do I need to use a tool? No
{ai_prefix}: [your response here]
```
"""
VISUAL_CHATGPT_SUFFIX_CN = """你对文件名的正确性非常严格,而且永远不会伪造不存在的文件。
开始!
因为Visual ChatGPT是一个文本语言模型,必须使用工具去观察图片而不是依靠想象。
推理想法和观察结果只对Visual ChatGPT可见,需要记得在最终回复时把重要的信息重复给用户,你只能给用户返回中文句子。我们一步一步思考。在你使用工具时,工具的参数只能是英文。
聊天历史:
{chat_history}
新输入: {input}
Thought: Do I need to use a tool? {agent_scratchpad}
"""
os.makedirs('image', exist_ok=True)
def seed_everything(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
return seed
def prompts(name, description):
def decorator(func):
func.name = name
func.description = description
return func
return decorator
def blend_gt2pt(old_image, new_image, sigma=0.15, steps=100):
new_size = new_image.size
old_size = old_image.size
easy_img = np.array(new_image)
gt_img_array = np.array(old_image)
pos_w = (new_size[0] - old_size[0]) // 2
pos_h = (new_size[1] - old_size[1]) // 2
kernel_h = cv2.getGaussianKernel(old_size[1], old_size[1] * sigma)
kernel_w = cv2.getGaussianKernel(old_size[0], old_size[0] * sigma)
kernel = np.multiply(kernel_h, np.transpose(kernel_w))
kernel[steps:-steps, steps:-steps] = 1
kernel[:steps, :steps] = kernel[:steps, :steps] / kernel[steps - 1, steps - 1]
kernel[:steps, -steps:] = kernel[:steps, -steps:] / kernel[steps - 1, -(steps)]
kernel[-steps:, :steps] = kernel[-steps:, :steps] / kernel[-steps, steps - 1]
kernel[-steps:, -steps:] = kernel[-steps:, -steps:] / kernel[-steps, -steps]
kernel = np.expand_dims(kernel, 2)
kernel = np.repeat(kernel, 3, 2)
weight = np.linspace(0, 1, steps)
top = np.expand_dims(weight, 1)
top = np.repeat(top, old_size[0] - 2 * steps, 1)
top = np.expand_dims(top, 2)
top = np.repeat(top, 3, 2)
weight = np.linspace(1, 0, steps)
down = np.expand_dims(weight, 1)
down = np.repeat(down, old_size[0] - 2 * steps, 1)
down = np.expand_dims(down, 2)
down = np.repeat(down, 3, 2)
weight = np.linspace(0, 1, steps)
left = np.expand_dims(weight, 0)
left = np.repeat(left, old_size[1] - 2 * steps, 0)
left = np.expand_dims(left, 2)
left = np.repeat(left, 3, 2)
weight = np.linspace(1, 0, steps)
right = np.expand_dims(weight, 0)
right = np.repeat(right, old_size[1] - 2 * steps, 0)
right = np.expand_dims(right, 2)
right = np.repeat(right, 3, 2)
kernel[:steps, steps:-steps] = top
kernel[-steps:, steps:-steps] = down
kernel[steps:-steps, :steps] = left
kernel[steps:-steps, -steps:] = right
pt_gt_img = easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]]
gaussian_gt_img = kernel * gt_img_array + (1 - kernel) * pt_gt_img # gt img with blur img
gaussian_gt_img = gaussian_gt_img.astype(np.int64)
easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]] = gaussian_gt_img
gaussian_img = Image.fromarray(easy_img)
return gaussian_img
def cut_dialogue_history(history_memory, keep_last_n_words=500):
if history_memory is None or len(history_memory) == 0:
return history_memory
tokens = history_memory.split()
n_tokens = len(tokens)
print(f"history_memory:{history_memory}, n_tokens: {n_tokens}")
if n_tokens < keep_last_n_words:
return history_memory
paragraphs = history_memory.split('\n')
last_n_tokens = n_tokens
while last_n_tokens >= keep_last_n_words:
last_n_tokens -= len(paragraphs[0].split(' '))
paragraphs = paragraphs[1:]
return '\n' + '\n'.join(paragraphs)
def get_new_image_name(org_img_name, func_name="update"):
head_tail = os.path.split(org_img_name)
head = head_tail[0]
tail = head_tail[1]
name_split = tail.split('.')[0].split('_')
this_new_uuid = str(uuid.uuid4())[:4]
if len(name_split) == 1:
most_org_file_name = name_split[0]
else:
assert len(name_split) == 4
most_org_file_name = name_split[3]
recent_prev_file_name = name_split[0]
new_file_name = f'{this_new_uuid}_{func_name}_{recent_prev_file_name}_{most_org_file_name}.png'
return os.path.join(head, new_file_name)
class InstructPix2Pix:
def __init__(self, device):
print(f"Initializing InstructPix2Pix to {device}")
self.device = device
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix",
safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),
torch_dtype=self.torch_dtype).to(device)
self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)
@prompts(name="Instruct Image Using Text",
description="useful when you want to the style of the image to be like the text. "
"like: make it look like a painting. or make it like a robot. "
"The input to this tool should be a comma separated string of two, "
"representing the image_path and the text. ")
def inference(self, inputs):
"""Change style of image."""
print("===>Starting InstructPix2Pix Inference")
image_path, text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
original_image = Image.open(image_path)
image = self.pipe(text, image=original_image, num_inference_steps=40, image_guidance_scale=1.2).images[0]
updated_image_path = get_new_image_name(image_path, func_name="pix2pix")
image.save(updated_image_path)
print(f"\nProcessed InstructPix2Pix, Input Image: {image_path}, Instruct Text: {text}, "
f"Output Image: {updated_image_path}")
return updated_image_path
class Text2Image:
def __init__(self, device):
print(f"Initializing Text2Image to {device}")
self.device = device
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5",
torch_dtype=self.torch_dtype)
self.pipe.to(device)
self.a_prompt = 'best quality, extremely detailed'
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
'fewer digits, cropped, worst quality, low quality'
@prompts(name="Generate Image From User Input Text",
description="useful when you want to generate an image from a user input text and save it to a file. "
"like: generate an image of an object or something, or generate an image that includes some objects. "
"The input to this tool should be a string, representing the text used to generate image. ")
def inference(self, text):
image_filename = os.path.join('image', f"{str(uuid.uuid4())[:8]}.png")
prompt = text + ', ' + self.a_prompt
image = self.pipe(prompt, negative_prompt=self.n_prompt).images[0]
image.save(image_filename)
print(
f"\nProcessed Text2Image, Input Text: {text}, Output Image: {image_filename}")
return image_filename
class ImageCaptioning:
def __init__(self, device):
print(f"Initializing ImageCaptioning to {device}")
self.device = device
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
self.model = BlipForConditionalGeneration.from_pretrained(
"Salesforce/blip-image-captioning-base", torch_dtype=self.torch_dtype).to(self.device)
@prompts(name="Get Photo Description",
description="useful when you want to know what is inside the photo. receives image_path as input. "
"The input to this tool should be a string, representing the image_path. ")
def inference(self, image_path):
inputs = self.processor(Image.open(image_path), return_tensors="pt").to(self.device, self.torch_dtype)
out = self.model.generate(**inputs)
captions = self.processor.decode(out[0], skip_special_tokens=True)
print(f"\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}")
return captions
class Image2Canny:
def __init__(self, device):
print("Initializing Image2Canny")
self.low_threshold = 100
self.high_threshold = 200
@prompts(name="Edge Detection On Image",
description="useful when you want to detect the edge of the image. "
"like: detect the edges of this image, or canny detection on image, "
"or perform edge detection on this image, or detect the canny image of this image. "
"The input to this tool should be a string, representing the image_path")
def inference(self, inputs):
image = Image.open(inputs)
image = np.array(image)
canny = cv2.Canny(image, self.low_threshold, self.high_threshold)
canny = canny[:, :, None]
canny = np.concatenate([canny, canny, canny], axis=2)
canny = Image.fromarray(canny)
updated_image_path = get_new_image_name(inputs, func_name="edge")
canny.save(updated_image_path)
print(f"\nProcessed Image2Canny, Input Image: {inputs}, Output Text: {updated_image_path}")
return updated_image_path
class CannyText2Image:
def __init__(self, device):
print(f"Initializing CannyText2Image to {device}")
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-canny",
torch_dtype=self.torch_dtype)
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),
torch_dtype=self.torch_dtype)
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
self.pipe.to(device)
self.seed = -1
self.a_prompt = 'best quality, extremely detailed'
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
'fewer digits, cropped, worst quality, low quality'
@prompts(name="Generate Image Condition On Canny Image",
description="useful when you want to generate a new real image from both the user description and a canny image."
" like: generate a real image of a object or something from this canny image,"
" or generate a new real image of a object or something from this edge image. "
"The input to this tool should be a comma separated string of two, "
"representing the image_path and the user description. ")
def inference(self, inputs):
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
image = Image.open(image_path)
self.seed = random.randint(0, 65535)
seed_everything(self.seed)
prompt = f'{instruct_text}, {self.a_prompt}'
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
guidance_scale=9.0).images[0]
updated_image_path = get_new_image_name(image_path, func_name="canny2image")
image.save(updated_image_path)
print(f"\nProcessed CannyText2Image, Input Canny: {image_path}, Input Text: {instruct_text}, "
f"Output Text: {updated_image_path}")
return updated_image_path
class Image2Line:
def __init__(self, device):
print("Initializing Image2Line")
self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')
@prompts(name="Line Detection On Image",
description="useful when you want to detect the straight line of the image. "
"like: detect the straight lines of this image, or straight line detection on image, "
"or perform straight line detection on this image, or detect the straight line image of this image. "
"The input to this tool should be a string, representing the image_path")
def inference(self, inputs):
image = Image.open(inputs)
mlsd = self.detector(image)
updated_image_path = get_new_image_name(inputs, func_name="line-of")
mlsd.save(updated_image_path)
print(f"\nProcessed Image2Line, Input Image: {inputs}, Output Line: {updated_image_path}")
return updated_image_path
class LineText2Image:
def __init__(self, device):
print(f"Initializing LineText2Image to {device}")
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-mlsd",
torch_dtype=self.torch_dtype)
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),
torch_dtype=self.torch_dtype
)
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
self.pipe.to(device)
self.seed = -1
self.a_prompt = 'best quality, extremely detailed'
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
'fewer digits, cropped, worst quality, low quality'
@prompts(name="Generate Image Condition On Line Image",
description="useful when you want to generate a new real image from both the user description "
"and a straight line image. "
"like: generate a real image of a object or something from this straight line image, "
"or generate a new real image of a object or something from this straight lines. "
"The input to this tool should be a comma separated string of two, "
"representing the image_path and the user description. ")
def inference(self, inputs):
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
image = Image.open(image_path)
self.seed = random.randint(0, 65535)
seed_everything(self.seed)
prompt = f'{instruct_text}, {self.a_prompt}'
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
guidance_scale=9.0).images[0]
updated_image_path = get_new_image_name(image_path, func_name="line2image")
image.save(updated_image_path)
print(f"\nProcessed LineText2Image, Input Line: {image_path}, Input Text: {instruct_text}, "
f"Output Text: {updated_image_path}")
return updated_image_path
class Image2Hed:
def __init__(self, device):
print("Initializing Image2Hed")
self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')
@prompts(name="Hed Detection On Image",
description="useful when you want to detect the soft hed boundary of the image. "
"like: detect the soft hed boundary of this image, or hed boundary detection on image, "
"or perform hed boundary detection on this image, or detect soft hed boundary image of this image. "
"The input to this tool should be a string, representing the image_path")
def inference(self, inputs):
image = Image.open(inputs)
hed = self.detector(image)
updated_image_path = get_new_image_name(inputs, func_name="hed-boundary")
hed.save(updated_image_path)
print(f"\nProcessed Image2Hed, Input Image: {inputs}, Output Hed: {updated_image_path}")
return updated_image_path
class HedText2Image:
def __init__(self, device):
print(f"Initializing HedText2Image to {device}")
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-hed",
torch_dtype=self.torch_dtype)
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),
torch_dtype=self.torch_dtype
)
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
self.pipe.to(device)
self.seed = -1
self.a_prompt = 'best quality, extremely detailed'
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
'fewer digits, cropped, worst quality, low quality'
@prompts(name="Generate Image Condition On Soft Hed Boundary Image",
description="useful when you want to generate a new real image from both the user description "
"and a soft hed boundary image. "
"like: generate a real image of a object or something from this soft hed boundary image, "
"or generate a new real image of a object or something from this hed boundary. "
"The input to this tool should be a comma separated string of two, "
"representing the image_path and the user description")
def inference(self, inputs):
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
image = Image.open(image_path)
self.seed = random.randint(0, 65535)
seed_everything(self.seed)
prompt = f'{instruct_text}, {self.a_prompt}'
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
guidance_scale=9.0).images[0]
updated_image_path = get_new_image_name(image_path, func_name="hed2image")
image.save(updated_image_path)
print(f"\nProcessed HedText2Image, Input Hed: {image_path}, Input Text: {instruct_text}, "
f"Output Image: {updated_image_path}")
return updated_image_path
class Image2Scribble:
def __init__(self, device):
print("Initializing Image2Scribble")
self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')
@prompts(name="Sketch Detection On Image",
description="useful when you want to generate a scribble of the image. "
"like: generate a scribble of this image, or generate a sketch from this image, "
"detect the sketch from this image. "
"The input to this tool should be a string, representing the image_path")
def inference(self, inputs):
image = Image.open(inputs)
scribble = self.detector(image, scribble=True)
updated_image_path = get_new_image_name(inputs, func_name="scribble")
scribble.save(updated_image_path)
print(f"\nProcessed Image2Scribble, Input Image: {inputs}, Output Scribble: {updated_image_path}")
return updated_image_path
class ScribbleText2Image:
def __init__(self, device):
print(f"Initializing ScribbleText2Image to {device}")
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-scribble",
torch_dtype=self.torch_dtype)
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),
torch_dtype=self.torch_dtype
)
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
self.pipe.to(device)
self.seed = -1
self.a_prompt = 'best quality, extremely detailed'
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
'fewer digits, cropped, worst quality, low quality'
@prompts(name="Generate Image Condition On Sketch Image",
description="useful when you want to generate a new real image from both the user description and "
"a scribble image or a sketch image. "
"The input to this tool should be a comma separated string of two, "
"representing the image_path and the user description")
def inference(self, inputs):
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
image = Image.open(image_path)
self.seed = random.randint(0, 65535)
seed_everything(self.seed)
prompt = f'{instruct_text}, {self.a_prompt}'
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
guidance_scale=9.0).images[0]
updated_image_path = get_new_image_name(image_path, func_name="scribble2image")
image.save(updated_image_path)
print(f"\nProcessed ScribbleText2Image, Input Scribble: {image_path}, Input Text: {instruct_text}, "
f"Output Image: {updated_image_path}")
return updated_image_path
class Image2Pose:
def __init__(self, device):
print("Initializing Image2Pose")
self.detector = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')
@prompts(name="Pose Detection On Image",
description="useful when you want to detect the human pose of the image. "
"like: generate human poses of this image, or generate a pose image from this image. "
"The input to this tool should be a string, representing the image_path")
def inference(self, inputs):
image = Image.open(inputs)
pose = self.detector(image)
updated_image_path = get_new_image_name(inputs, func_name="human-pose")
pose.save(updated_image_path)
print(f"\nProcessed Image2Pose, Input Image: {inputs}, Output Pose: {updated_image_path}")
return updated_image_path
class PoseText2Image:
def __init__(self, device):
print(f"Initializing PoseText2Image to {device}")
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-openpose",
torch_dtype=self.torch_dtype)
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),
torch_dtype=self.torch_dtype)
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
self.pipe.to(device)
self.num_inference_steps = 20
self.seed = -1
self.unconditional_guidance_scale = 9.0
self.a_prompt = 'best quality, extremely detailed'
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
' fewer digits, cropped, worst quality, low quality'
@prompts(name="Generate Image Condition On Pose Image",
description="useful when you want to generate a new real image from both the user description "
"and a human pose image. "
"like: generate a real image of a human from this human pose image, "
"or generate a new real image of a human from this pose. "
"The input to this tool should be a comma separated string of two, "
"representing the image_path and the user description")
def inference(self, inputs):
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
image = Image.open(image_path)
self.seed = random.randint(0, 65535)
seed_everything(self.seed)
prompt = f'{instruct_text}, {self.a_prompt}'
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
guidance_scale=9.0).images[0]
updated_image_path = get_new_image_name(image_path, func_name="pose2image")
image.save(updated_image_path)
print(f"\nProcessed PoseText2Image, Input Pose: {image_path}, Input Text: {instruct_text}, "
f"Output Image: {updated_image_path}")
return updated_image_path
class SegText2Image:
def __init__(self, device):
print(f"Initializing SegText2Image to {device}")
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-seg",
torch_dtype=self.torch_dtype)
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),
torch_dtype=self.torch_dtype)
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
self.pipe.to(device)
self.seed = -1
self.a_prompt = 'best quality, extremely detailed'
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
' fewer digits, cropped, worst quality, low quality'
@prompts(name="Generate Image Condition On Segmentations",
description="useful when you want to generate a new real image from both the user description and segmentations. "
"like: generate a real image of a object or something from this segmentation image, "
"or generate a new real image of a object or something from these segmentations. "
"The input to this tool should be a comma separated string of two, "
"representing the image_path and the user description")
def inference(self, inputs):
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
image = Image.open(image_path)
self.seed = random.randint(0, 65535)
seed_everything(self.seed)
prompt = f'{instruct_text}, {self.a_prompt}'
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
guidance_scale=9.0).images[0]
updated_image_path = get_new_image_name(image_path, func_name="segment2image")
image.save(updated_image_path)
print(f"\nProcessed SegText2Image, Input Seg: {image_path}, Input Text: {instruct_text}, "
f"Output Image: {updated_image_path}")
return updated_image_path
class Image2Depth:
def __init__(self, device):
print("Initializing Image2Depth")
self.depth_estimator = pipeline('depth-estimation')
@prompts(name="Predict Depth On Image",
description="useful when you want to detect depth of the image. like: generate the depth from this image, "
"or detect the depth map on this image, or predict the depth for this image. "
"The input to this tool should be a string, representing the image_path")
def inference(self, inputs):
image = Image.open(inputs)
depth = self.depth_estimator(image)['depth']
depth = np.array(depth)
depth = depth[:, :, None]
depth = np.concatenate([depth, depth, depth], axis=2)
depth = Image.fromarray(depth)
updated_image_path = get_new_image_name(inputs, func_name="depth")
depth.save(updated_image_path)
print(f"\nProcessed Image2Depth, Input Image: {inputs}, Output Depth: {updated_image_path}")
return updated_image_path
class DepthText2Image:
def __init__(self, device):
print(f"Initializing DepthText2Image to {device}")
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.controlnet = ControlNetModel.from_pretrained(
"fusing/stable-diffusion-v1-5-controlnet-depth", torch_dtype=self.torch_dtype)
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),
torch_dtype=self.torch_dtype)
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
self.pipe.to(device)
self.seed = -1
self.a_prompt = 'best quality, extremely detailed'
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
' fewer digits, cropped, worst quality, low quality'
@prompts(name="Generate Image Condition On Depth",
description="useful when you want to generate a new real image from both the user description and depth image. "
"like: generate a real image of a object or something from this depth image, "
"or generate a new real image of a object or something from the depth map. "
"The input to this tool should be a comma separated string of two, "
"representing the image_path and the user description")
def inference(self, inputs):
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
image = Image.open(image_path)
self.seed = random.randint(0, 65535)
seed_everything(self.seed)
prompt = f'{instruct_text}, {self.a_prompt}'
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
guidance_scale=9.0).images[0]
updated_image_path = get_new_image_name(image_path, func_name="depth2image")
image.save(updated_image_path)
print(f"\nProcessed DepthText2Image, Input Depth: {image_path}, Input Text: {instruct_text}, "
f"Output Image: {updated_image_path}")
return updated_image_path
class Image2Normal:
def __init__(self, device):
print("Initializing Image2Normal")
self.depth_estimator = pipeline("depth-estimation", model="Intel/dpt-hybrid-midas")
self.bg_threhold = 0.4
@prompts(name="Predict Normal Map On Image",
description="useful when you want to detect norm map of the image. "
"like: generate normal map from this image, or predict normal map of this image. "
"The input to this tool should be a string, representing the image_path")
def inference(self, inputs):
image = Image.open(inputs)
original_size = image.size
image = self.depth_estimator(image)['predicted_depth'][0]
image = image.numpy()
image_depth = image.copy()
image_depth -= np.min(image_depth)
image_depth /= np.max(image_depth)
x = cv2.Sobel(image, cv2.CV_32F, 1, 0, ksize=3)
x[image_depth < self.bg_threhold] = 0
y = cv2.Sobel(image, cv2.CV_32F, 0, 1, ksize=3)
y[image_depth < self.bg_threhold] = 0
z = np.ones_like(x) * np.pi * 2.0
image = np.stack([x, y, z], axis=2)
image /= np.sum(image ** 2.0, axis=2, keepdims=True) ** 0.5
image = (image * 127.5 + 127.5).clip(0, 255).astype(np.uint8)
image = Image.fromarray(image)
image = image.resize(original_size)
updated_image_path = get_new_image_name(inputs, func_name="normal-map")
image.save(updated_image_path)
print(f"\nProcessed Image2Normal, Input Image: {inputs}, Output Depth: {updated_image_path}")
return updated_image_path
class NormalText2Image:
def __init__(self, device):
print(f"Initializing NormalText2Image to {device}")
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.controlnet = ControlNetModel.from_pretrained(
"fusing/stable-diffusion-v1-5-controlnet-normal", torch_dtype=self.torch_dtype)
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),
torch_dtype=self.torch_dtype)
self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)
self.pipe.to(device)
self.seed = -1
self.a_prompt = 'best quality, extremely detailed'
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \
' fewer digits, cropped, worst quality, low quality'
@prompts(name="Generate Image Condition On Normal Map",
description="useful when you want to generate a new real image from both the user description and normal map. "
"like: generate a real image of a object or something from this normal map, "
"or generate a new real image of a object or something from the normal map. "
"The input to this tool should be a comma separated string of two, "
"representing the image_path and the user description")
def inference(self, inputs):
image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
image = Image.open(image_path)
self.seed = random.randint(0, 65535)
seed_everything(self.seed)
prompt = f'{instruct_text}, {self.a_prompt}'
image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,
guidance_scale=9.0).images[0]
updated_image_path = get_new_image_name(image_path, func_name="normal2image")
image.save(updated_image_path)
print(f"\nProcessed NormalText2Image, Input Normal: {image_path}, Input Text: {instruct_text}, "
f"Output Image: {updated_image_path}")
return updated_image_path
class VisualQuestionAnswering:
def __init__(self, device):
print(f"Initializing VisualQuestionAnswering to {device}")
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.device = device
self.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
self.model = BlipForQuestionAnswering.from_pretrained(
"Salesforce/blip-vqa-base", torch_dtype=self.torch_dtype).to(self.device)
@prompts(name="Answer Question About The Image",
description="useful when you need an answer for a question based on an image. "
"like: what is the background color of the last image, how many cats in this figure, what is in this figure. "
"The input to this tool should be a comma separated string of two, representing the image_path and the question")
def inference(self, inputs):
image_path, question = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
raw_image = Image.open(image_path).convert('RGB')
inputs = self.processor(raw_image, question, return_tensors="pt").to(self.device, self.torch_dtype)
out = self.model.generate(**inputs)
answer = self.processor.decode(out[0], skip_special_tokens=True)
print(f"\nProcessed VisualQuestionAnswering, Input Image: {image_path}, Input Question: {question}, "
f"Output Answer: {answer}")
return answer
class Segmenting:
def __init__(self, device):
print(f"Inintializing Segmentation to {device}")
self.device = device
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.model_checkpoint_path = os.path.join("checkpoints","sam")
self.download_parameters()
self.sam = build_sam(checkpoint=self.model_checkpoint_path).to(device)
self.sam_predictor = SamPredictor(self.sam)
self.mask_generator = SamAutomaticMaskGenerator(self.sam)
self.saved_points = []
self.saved_labels = []
def download_parameters(self):
url = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"
if not os.path.exists(self.model_checkpoint_path):
wget.download(url,out=self.model_checkpoint_path)
def show_mask(self, mask: np.ndarray,image: np.ndarray,
random_color: bool = False, transparency=1) -> np.ndarray:
"""Visualize a mask on top of an image.
Args:
mask (np.ndarray): A 2D array of shape (H, W).
image (np.ndarray): A 3D array of shape (H, W, 3).
random_color (bool): Whether to use a random color for the mask.
Outputs:
np.ndarray: A 3D array of shape (H, W, 3) with the mask
visualized on top of the image.
transparenccy: the transparency of the segmentation mask
"""
if random_color:
color = np.concatenate([np.random.random(3)], axis=0)
else:
color = np.array([30 / 255, 144 / 255, 255 / 255])
h, w = mask.shape[-2:]
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1) * 255
image = cv2.addWeighted(image, 0.7, mask_image.astype('uint8'), transparency, 0)
return image
def show_box(self, box, ax, label):
x0, y0 = box[0], box[1]
w, h = box[2] - box[0], box[3] - box[1]
ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2))
ax.text(x0, y0, label)
def get_mask_with_boxes(self, image_pil, image, boxes_filt):
size = image_pil.size
H, W = size[1], size[0]
for i in range(boxes_filt.size(0)):
boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])
boxes_filt[i][:2] -= boxes_filt[i][2:] / 2
boxes_filt[i][2:] += boxes_filt[i][:2]
boxes_filt = boxes_filt.cpu()
transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(self.device)
masks, _, _ = self.sam_predictor.predict_torch(
point_coords = None,
point_labels = None,
boxes = transformed_boxes.to(self.device),
multimask_output = False,
)
return masks
def segment_image_with_boxes(self, image_pil, image_path, boxes_filt, pred_phrases):
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
self.sam_predictor.set_image(image)
masks = self.get_mask_with_boxes(image_pil, image, boxes_filt)
# draw output image
for mask in masks:
image = self.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)
updated_image_path = get_new_image_name(image_path, func_name="segmentation")
new_image = Image.fromarray(image)
new_image.save(updated_image_path)
return updated_image_path
def set_image(self, img) -> None:
"""Set the image for the predictor."""
with torch.cuda.amp.autocast():
self.sam_predictor.set_image(img)
def show_points(self, coords: np.ndarray, labels: np.ndarray,
image: np.ndarray) -> np.ndarray:
"""Visualize points on top of an image.
Args:
coords (np.ndarray): A 2D array of shape (N, 2).
labels (np.ndarray): A 1D array of shape (N,).
image (np.ndarray): A 3D array of shape (H, W, 3).
Returns:
np.ndarray: A 3D array of shape (H, W, 3) with the points
visualized on top of the image.
"""
pos_points = coords[labels == 1]
neg_points = coords[labels == 0]
for p in pos_points:
image = cv2.circle(
image, p.astype(int), radius=3, color=(0, 255, 0), thickness=-1)
for p in neg_points:
image = cv2.circle(
image, p.astype(int), radius=3, color=(255, 0, 0), thickness=-1)
return image
def segment_image_with_click(self, img, is_positive: bool,
evt: gr.SelectData):
self.sam_predictor.set_image(img)
self.saved_points.append([evt.index[0], evt.index[1]])
self.saved_labels.append(1 if is_positive else 0)
input_point = np.array(self.saved_points)
input_label = np.array(self.saved_labels)
# Predict the mask
with torch.cuda.amp.autocast():
masks, scores, logits = self.sam_predictor.predict(
point_coords=input_point,
point_labels=input_label,
multimask_output=False,
)
img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)
img = self.show_points(input_point, input_label, img)
return img
def segment_image_with_coordinate(self, img, is_positive: bool,
coordinate: tuple):
'''
Args:
img (numpy.ndarray): the given image, shape: H x W x 3.
is_positive: whether the click is positive, if want to add mask use True else False.
coordinate: the position of the click
If the position is (x,y), means click at the x-th column and y-th row of the pixel matrix.
So x correspond to W, and y correspond to H.
Output:
img (PLI.Image.Image): the result image
result_mask (numpy.ndarray): the result mask, shape: H x W
Other parameters:
transparency (float): the transparenccy of the mask
to control he degree of transparency after the mask is superimposed.
if transparency=1, then the masked part will be completely replaced with other colors.
'''
self.sam_predictor.set_image(img)
self.saved_points.append([coordinate[0], coordinate[1]])
self.saved_labels.append(1 if is_positive else 0)
input_point = np.array(self.saved_points)
input_label = np.array(self.saved_labels)
# Predict the mask
with torch.cuda.amp.autocast():
masks, scores, logits = self.sam_predictor.predict(
point_coords=input_point,
point_labels=input_label,
multimask_output=False,
)
img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)
img = self.show_points(input_point, input_label, img)
img = Image.fromarray(img)
result_mask = masks[0]
return img, result_mask
@prompts(name="Segment the Image",
description="useful when you want to segment all the part of the image, but not segment a certain object."
"like: segment all the object in this image, or generate segmentations on this image, "
"or segment the image,"
"or perform segmentation on this image, "
"or segment all the object in this image."
"The input to this tool should be a string, representing the image_path")
def inference_all(self,image_path):
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
masks = self.mask_generator.generate(image)
plt.figure(figsize=(20,20))
plt.imshow(image)
if len(masks) == 0:
return
sorted_anns = sorted(masks, key=(lambda x: x['area']), reverse=True)
ax = plt.gca()
ax.set_autoscale_on(False)
polygons = []
color = []
for ann in sorted_anns:
m = ann['segmentation']
img = np.ones((m.shape[0], m.shape[1], 3))
color_mask = np.random.random((1, 3)).tolist()[0]
for i in range(3):
img[:,:,i] = color_mask[i]
ax.imshow(np.dstack((img, m)))
updated_image_path = get_new_image_name(image_path, func_name="segment-image")
plt.axis('off')
plt.savefig(
updated_image_path,
bbox_inches="tight", dpi=300, pad_inches=0.0
)
return updated_image_path
class Text2Box:
def __init__(self, device):
print(f"Initializing ObjectDetection to {device}")
self.device = device
self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
self.model_checkpoint_path = os.path.join("checkpoints","groundingdino")
self.model_config_path = os.path.join("checkpoints","grounding_config.py")
self.download_parameters()
self.box_threshold = 0.3
self.text_threshold = 0.25
self.grounding = (self.load_model()).to(self.device)
def download_parameters(self):
url = "https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth"
if not os.path.exists(self.model_checkpoint_path):
wget.download(url,out=self.model_checkpoint_path)
config_url = "https://raw.githubusercontent.com/IDEA-Research/GroundingDINO/main/groundingdino/config/GroundingDINO_SwinT_OGC.py"
if not os.path.exists(self.model_config_path):
wget.download(config_url,out=self.model_config_path)
def load_image(self,image_path):
# load image
image_pil = Image.open(image_path).convert("RGB") # load image
transform = T.Compose(
[
T.RandomResize([512], max_size=1333),
T.ToTensor(),
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
)
image, _ = transform(image_pil, None) # 3, h, w
return image_pil, image
def load_model(self):
args = SLConfig.fromfile(self.model_config_path)
args.device = self.device
model = build_model(args)
checkpoint = torch.load(self.model_checkpoint_path, map_location="cpu")
load_res = model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
print(load_res)
_ = model.eval()
return model
def get_grounding_boxes(self, image, caption, with_logits=True):
caption = caption.lower()
caption = caption.strip()
if not caption.endswith("."):
caption = caption + "."
image = image.to(self.device)
with torch.no_grad():
outputs = self.grounding(image[None], captions=[caption])
logits = outputs["pred_logits"].cpu().sigmoid()[0] # (nq, 256)
boxes = outputs["pred_boxes"].cpu()[0] # (nq, 4)
logits.shape[0]
# filter output
logits_filt = logits.clone()
boxes_filt = boxes.clone()
filt_mask = logits_filt.max(dim=1)[0] > self.box_threshold
logits_filt = logits_filt[filt_mask] # num_filt, 256
boxes_filt = boxes_filt[filt_mask] # num_filt, 4
logits_filt.shape[0]
# get phrase
tokenlizer = self.grounding.tokenizer
tokenized = tokenlizer(caption)
# build pred
pred_phrases = []
for logit, box in zip(logits_filt, boxes_filt):
pred_phrase = get_phrases_from_posmap(logit > self.text_threshold, tokenized, tokenlizer)
if with_logits:
pred_phrases.append(pred_phrase + f"({str(logit.max().item())[:4]})")
else:
pred_phrases.append(pred_phrase)
return boxes_filt, pred_phrases
def plot_boxes_to_image(self, image_pil, tgt):
H, W = tgt["size"]
boxes = tgt["boxes"]
labels = tgt["labels"]
assert len(boxes) == len(labels), "boxes and labels must have same length"
draw = ImageDraw.Draw(image_pil)
mask = Image.new("L", image_pil.size, 0)
mask_draw = ImageDraw.Draw(mask)
# draw boxes and masks
for box, label in zip(boxes, labels):
# from 0..1 to 0..W, 0..H
box = box * torch.Tensor([W, H, W, H])
# from xywh to xyxy
box[:2] -= box[2:] / 2
box[2:] += box[:2]
# random color
color = tuple(np.random.randint(0, 255, size=3).tolist())
# draw
x0, y0, x1, y1 = box
x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)
draw.rectangle([x0, y0, x1, y1], outline=color, width=6)
# draw.text((x0, y0), str(label), fill=color)
font = ImageFont.load_default()
if hasattr(font, "getbbox"):
bbox = draw.textbbox((x0, y0), str(label), font)
else:
w, h = draw.textsize(str(label), font)
bbox = (x0, y0, w + x0, y0 + h)
# bbox = draw.textbbox((x0, y0), str(label))
draw.rectangle(bbox, fill=color)
draw.text((x0, y0), str(label), fill="white")
mask_draw.rectangle([x0, y0, x1, y1], fill=255, width=2)
return image_pil, mask
@prompts(name="Detect the Give Object",
description="useful when you only want to detect or find out given objects in the picture"
"The input to this tool should be a comma separated string of two, "
"representing the image_path, the text description of the object to be found")
def inference(self, inputs):
image_path, det_prompt = inputs.split(",")
print(f"image_path={image_path}, text_prompt={det_prompt}")
image_pil, image = self.load_image(image_path)
boxes_filt, pred_phrases = self.get_grounding_boxes(image, det_prompt)
size = image_pil.size
pred_dict = {
"boxes": boxes_filt,
"size": [size[1], size[0]], # H,W
"labels": pred_phrases,}
image_with_box = self.plot_boxes_to_image(image_pil, pred_dict)[0]
updated_image_path = get_new_image_name(image_path, func_name="detect-something")
updated_image = image_with_box.resize(size)
updated_image.save(updated_image_path)
print(
f"\nProcessed ObejectDetecting, Input Image: {image_path}, Object to be Detect {det_prompt}, "
f"Output Image: {updated_image_path}")
return updated_image_path
class Inpainting:
def __init__(self, device):
self.device = device
self.revision = 'fp16' if 'cuda' in self.device else None
self.torch_dtype = torch.float16 if 'cuda' in self.device else torch.float32
self.inpaint = StableDiffusionInpaintPipeline.from_pretrained(
"runwayml/stable-diffusion-inpainting", revision=self.revision, torch_dtype=self.torch_dtype,safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker')).to(device)
def __call__(self, prompt, image, mask_image, height=512, width=512, num_inference_steps=50):
update_image = self.inpaint(prompt=prompt, image=image.resize((width, height)),
mask_image=mask_image.resize((width, height)), height=height, width=width, num_inference_steps=num_inference_steps).images[0]
return update_image
class InfinityOutPainting:
template_model = True # Add this line to show this is a template model.
def __init__(self, ImageCaptioning, Inpainting, VisualQuestionAnswering):
self.llm = OpenAI(temperature=0)
self.ImageCaption = ImageCaptioning
self.inpaint = Inpainting
self.ImageVQA = VisualQuestionAnswering
self.a_prompt = 'best quality, extremely detailed'
self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \
'fewer digits, cropped, worst quality, low quality'
def get_BLIP_vqa(self, image, question):
inputs = self.ImageVQA.processor(image, question, return_tensors="pt").to(self.ImageVQA.device,
self.ImageVQA.torch_dtype)
out = self.ImageVQA.model.generate(**inputs)
answer = self.ImageVQA.processor.decode(out[0], skip_special_tokens=True)
print(f"\nProcessed VisualQuestionAnswering, Input Question: {question}, Output Answer: {answer}")
return answer
def get_BLIP_caption(self, image):
inputs = self.ImageCaption.processor(image, return_tensors="pt").to(self.ImageCaption.device,
self.ImageCaption.torch_dtype)
out = self.ImageCaption.model.generate(**inputs)
BLIP_caption = self.ImageCaption.processor.decode(out[0], skip_special_tokens=True)
return BLIP_caption
def check_prompt(self, prompt):
check = f"Here is a paragraph with adjectives. " \
f"{prompt} " \
f"Please change all plural forms in the adjectives to singular forms. "
return self.llm(check)
def get_imagine_caption(self, image, imagine):
BLIP_caption = self.get_BLIP_caption(image)
background_color = self.get_BLIP_vqa(image, 'what is the background color of this image')
style = self.get_BLIP_vqa(image, 'what is the style of this image')
imagine_prompt = f"let's pretend you are an excellent painter and now " \
f"there is an incomplete painting with {BLIP_caption} in the center, " \
f"please imagine the complete painting and describe it" \
f"you should consider the background color is {background_color}, the style is {style}" \
f"You should make the painting as vivid and realistic as possible" \
f"You can not use words like painting or picture" \
f"and you should use no more than 50 words to describe it"
caption = self.llm(imagine_prompt) if imagine else BLIP_caption
caption = self.check_prompt(caption)
print(f'BLIP observation: {BLIP_caption}, ChatGPT imagine to {caption}') if imagine else print(
f'Prompt: {caption}')
return caption
def resize_image(self, image, max_size=1000000, multiple=8):
aspect_ratio = image.size[0] / image.size[1]
new_width = int(math.sqrt(max_size * aspect_ratio))
new_height = int(new_width / aspect_ratio)
new_width, new_height = new_width - (new_width % multiple), new_height - (new_height % multiple)
return image.resize((new_width, new_height))
def dowhile(self, original_img, tosize, expand_ratio, imagine, usr_prompt):
old_img = original_img
while (old_img.size != tosize):
prompt = self.check_prompt(usr_prompt) if usr_prompt else self.get_imagine_caption(old_img, imagine)
crop_w = 15 if old_img.size[0] != tosize[0] else 0
crop_h = 15 if old_img.size[1] != tosize[1] else 0
old_img = ImageOps.crop(old_img, (crop_w, crop_h, crop_w, crop_h))
temp_canvas_size = (expand_ratio * old_img.width if expand_ratio * old_img.width < tosize[0] else tosize[0],
expand_ratio * old_img.height if expand_ratio * old_img.height < tosize[1] else tosize[
1])
temp_canvas, temp_mask = Image.new("RGB", temp_canvas_size, color="white"), Image.new("L", temp_canvas_size,
color="white")
x, y = (temp_canvas.width - old_img.width) // 2, (temp_canvas.height - old_img.height) // 2
temp_canvas.paste(old_img, (x, y))
temp_mask.paste(0, (x, y, x + old_img.width, y + old_img.height))
resized_temp_canvas, resized_temp_mask = self.resize_image(temp_canvas), self.resize_image(temp_mask)
image = self.inpaint(prompt=prompt, image=resized_temp_canvas, mask_image=resized_temp_mask,
height=resized_temp_canvas.height, width=resized_temp_canvas.width,
num_inference_steps=50).resize(
(temp_canvas.width, temp_canvas.height), Image.ANTIALIAS)
image = blend_gt2pt(old_img, image)
old_img = image
return old_img
@prompts(name="Extend An Image",
description="useful when you need to extend an image into a larger image."
"like: extend the image into a resolution of 2048x1024, extend the image into 2048x1024. "
"The input to this tool should be a comma separated string of two, representing the image_path and the resolution of widthxheight")
def inference(self, inputs):
image_path, resolution = inputs.split(',')
width, height = resolution.split('x')
tosize = (int(width), int(height))
image = Image.open(image_path)
image = ImageOps.crop(image, (10, 10, 10, 10))
out_painted_image = self.dowhile(image, tosize, 4, True, False)
updated_image_path = get_new_image_name(image_path, func_name="outpainting")
out_painted_image.save(updated_image_path)
print(f"\nProcessed InfinityOutPainting, Input Image: {image_path}, Input Resolution: {resolution}, "
f"Output Image: {updated_image_path}")
return updated_image_path
class ObjectSegmenting:
template_model = True # Add this line to show this is a template model.
def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting):
# self.llm = OpenAI(temperature=0)
self.grounding = Text2Box
self.sam = Segmenting
@prompts(name="Segment the given object",
description="useful when you only want to segment the certain objects in the picture"
"according to the given text"
"like: segment the cat,"
"or can you segment an obeject for me"
"The input to this tool should be a comma separated string of two, "
"representing the image_path, the text description of the object to be found")
def inference(self, inputs):
image_path, det_prompt = inputs.split(",")
print(f"image_path={image_path}, text_prompt={det_prompt}")
image_pil, image = self.grounding.load_image(image_path)
boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, det_prompt)
updated_image_path = self.sam.segment_image_with_boxes(image_pil,image_path,boxes_filt,pred_phrases)
print(
f"\nProcessed ObejectSegmenting, Input Image: {image_path}, Object to be Segment {det_prompt}, "
f"Output Image: {updated_image_path}")
return updated_image_path
def merge_masks(self, masks):
'''
Args:
mask (numpy.ndarray): shape N x 1 x H x W
Outputs:
new_mask (numpy.ndarray): shape H x W
'''
if type(masks) == torch.Tensor:
x = masks
elif type(masks) == np.ndarray:
x = torch.tensor(masks,dtype=int)
else:
raise TypeError("the type of the input masks must be numpy.ndarray or torch.tensor")
x = x.squeeze(dim=1)
value, _ = x.max(dim=0)
new_mask = value.cpu().numpy()
new_mask.astype(np.uint8)
return new_mask
def get_mask(self, image_path, text_prompt):
print(f"image_path={image_path}, text_prompt={text_prompt}")
# image_pil (PIL.Image.Image) -> size: W x H
# image (numpy.ndarray) -> H x W x 3
image_pil, image = self.grounding.load_image(image_path)
boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, text_prompt)
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
self.sam.sam_predictor.set_image(image)
# masks (torch.tensor) -> N x 1 x H x W
masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)
# merged_mask -> H x W
merged_mask = self.merge_masks(masks)
# draw output image
for mask in masks:
image = self.sam.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)
merged_mask_image = Image.fromarray(merged_mask)
return merged_mask
class ImageEditing:
template_model = True
def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting, Inpainting:Inpainting):
print(f"Initializing ImageEditing")
self.sam = Segmenting
self.grounding = Text2Box
self.inpaint = Inpainting
def pad_edge(self,mask,padding):
#mask Tensor [H,W]
mask = mask.numpy()
true_indices = np.argwhere(mask)
mask_array = np.zeros_like(mask, dtype=bool)
for idx in true_indices:
padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)
mask_array[padded_slice] = True
new_mask = (mask_array * 255).astype(np.uint8)
#new_mask
return new_mask
@prompts(name="Remove Something From The Photo",
description="useful when you want to remove and object or something from the photo "
"from its description or location. "
"The input to this tool should be a comma separated string of two, "
"representing the image_path and the object need to be removed. ")
def inference_remove(self, inputs):
image_path, to_be_removed_txt = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
return self.inference_replace_sam(f"{image_path},{to_be_removed_txt},background")
@prompts(name="Replace Something From The Photo",
description="useful when you want to replace an object from the object description or "
"location with another object from its description. "
"The input to this tool should be a comma separated string of three, "
"representing the image_path, the object to be replaced, the object to be replaced with ")
def inference_replace_sam(self,inputs):
image_path, to_be_replaced_txt, replace_with_txt = inputs.split(",")
print(f"image_path={image_path}, to_be_replaced_txt={to_be_replaced_txt}")
image_pil, image = self.grounding.load_image(image_path)
boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, to_be_replaced_txt)
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
self.sam.sam_predictor.set_image(image)
masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)
mask = torch.sum(masks, dim=0).unsqueeze(0)
mask = torch.where(mask > 0, True, False)
mask = mask.squeeze(0).squeeze(0).cpu() #tensor
mask = self.pad_edge(mask,padding=20) #numpy
mask_image = Image.fromarray(mask)
updated_image = self.inpaint(prompt=replace_with_txt, image=image_pil,
mask_image=mask_image)
updated_image_path = get_new_image_name(image_path, func_name="replace-something")
updated_image = updated_image.resize(image_pil.size)
updated_image.save(updated_image_path)
print(
f"\nProcessed ImageEditing, Input Image: {image_path}, Replace {to_be_replaced_txt} to {replace_with_txt}, "
f"Output Image: {updated_image_path}")
return updated_image_path
class BackgroundRemoving:
'''
using to remove the background of the given picture
'''
template_model = True
def __init__(self,VisualQuestionAnswering:VisualQuestionAnswering, Text2Box:Text2Box, Segmenting:Segmenting):
self.vqa = VisualQuestionAnswering
self.obj_segmenting = ObjectSegmenting(Text2Box,Segmenting)
@prompts(name="Remove the background",
description="useful when you want to extract the object or remove the background,"
"the input should be a string image_path"
)
def inference(self, image_path):
'''
given a image, return the picture only contains the extracted main object
'''
updated_image_path = None
mask = self.get_mask(image_path)
image = Image.open(image_path)
mask = Image.fromarray(mask)
image.putalpha(mask)
updated_image_path = get_new_image_name(image_path, func_name="detect-something")
image.save(updated_image_path)
return updated_image_path
def get_mask(self, image_path):
'''
Description:
given an image path, return the mask of the main object.
Args:
image_path (string): the file path of the image
Outputs:
mask (numpy.ndarray): H x W
'''
vqa_input = f"{image_path}, what is the main object in the image?"
text_prompt = self.vqa.inference(vqa_input)
mask = self.obj_segmenting.get_mask(image_path,text_prompt)
return mask
class ConversationBot:
def __init__(self, load_dict):
# load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}
print(f"Initializing VisualChatGPT, load_dict={load_dict}")
if 'ImageCaptioning' not in load_dict:
raise ValueError("You have to load ImageCaptioning as a basic function for VisualChatGPT")
self.models = {}
# Load Basic Foundation Models
for class_name, device in load_dict.items():
self.models[class_name] = globals()[class_name](device=device)
# Load Template Foundation Models
for class_name, module in globals().items():
if getattr(module, 'template_model', False):
template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if k!='self'}
loaded_names = set([type(e).__name__ for e in self.models.values()])
if template_required_names.issubset(loaded_names):
self.models[class_name] = globals()[class_name](
**{name: self.models[name] for name in template_required_names})
print(f"All the Available Functions: {self.models}")
self.tools = []
for instance in self.models.values():
for e in dir(instance):
if e.startswith('inference'):
func = getattr(instance, e)
self.tools.append(Tool(name=func.name, description=func.description, func=func))
self.llm = OpenAI(temperature=0)
self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
def init_agent(self, lang):
self.memory.clear() #clear previous history
if lang=='English':
PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, VISUAL_CHATGPT_SUFFIX
place = "Enter text and press enter, or upload an image"
label_clear = "Clear"
else:
PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX_CN, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN, VISUAL_CHATGPT_SUFFIX_CN
place = "输入文字并回车,或者上传图片"
label_clear = "清除"
self.agent = initialize_agent(
self.tools,
self.llm,
agent="conversational-react-description",
verbose=True,
memory=self.memory,
return_intermediate_steps=True,
agent_kwargs={'prefix': PREFIX, 'format_instructions': FORMAT_INSTRUCTIONS,
'suffix': SUFFIX}, )
return gr.update(visible = True), gr.update(visible = False), gr.update(placeholder=place), gr.update(value=label_clear)
def run_text(self, text, state):
self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
res = self.agent({"input": text.strip()})
res['output'] = res['output'].replace("\\", "/")
response = re.sub('(image/[-\w]*.png)', lambda m: f'})*{m.group(0)}*', res['output'])
state = state + [(text, response)]
print(f"\nProcessed run_text, Input text: {text}\nCurrent state: {state}\n"
f"Current Memory: {self.agent.memory.buffer}")
return state, state
def run_image(self, image, state, txt, lang):
image_filename = os.path.join('image', f"{str(uuid.uuid4())[:8]}.png")
print("======>Auto Resize Image...")
img = Image.open(image.name)
width, height = img.size
ratio = min(512 / width, 512 / height)
width_new, height_new = (round(width * ratio), round(height * ratio))
width_new = int(np.round(width_new / 64.0)) * 64
height_new = int(np.round(height_new / 64.0)) * 64
img = img.resize((width_new, height_new))
img = img.convert('RGB')
img.save(image_filename, "PNG")
print(f"Resize image form {width}x{height} to {width_new}x{height_new}")
description = self.models['ImageCaptioning'].inference(image_filename)
if lang == 'Chinese':
Human_prompt = f'\nHuman: 提供一张名为 {image_filename}的图片。它的描述是: {description}。 这些信息帮助你理解这个图像,但是你应该使用工具来完成下面的任务,而不是直接从我的描述中想象。 如果你明白了, 说 \"收到\". \n'
AI_prompt = "收到。 "
else:
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'
AI_prompt = "Received. "
self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
state = state + [(f"*{image_filename}*", AI_prompt)]
print(f"\nProcessed run_image, Input image: {image_filename}\nCurrent state: {state}\n"
f"Current Memory: {self.agent.memory.buffer}")
return state, state, f'{txt} {image_filename} '
if __name__ == '__main__':
if not os.path.exists("checkpoints"):
os.mkdir("checkpoints")
parser = argparse.ArgumentParser()
parser.add_argument('--load', type=str, default="ImageCaptioning_cuda:0,Text2Image_cuda:0")
args = parser.parse_args()
load_dict = {e.split('_')[0].strip(): e.split('_')[1].strip() for e in args.load.split(',')}
bot = ConversationBot(load_dict=load_dict)
with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:
lang = gr.Radio(choices = ['Chinese','English'], value=None, label='Language')
chatbot = gr.Chatbot(elem_id="chatbot", label="Visual ChatGPT")
state = gr.State([])
with gr.Row(visible=False) as input_raws:
with gr.Column(scale=0.7):
txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(
container=False)
with gr.Column(scale=0.15, min_width=0):
clear = gr.Button("Clear")
with gr.Column(scale=0.15, min_width=0):
btn = gr.UploadButton(label="🖼️",file_types=["image"])
lang.change(bot.init_agent, [lang], [input_raws, lang, txt, clear])
txt.submit(bot.run_text, [txt, state], [chatbot, state])
txt.submit(lambda: "", None, txt)
btn.upload(bot.run_image, [btn, state, txt, lang], [chatbot, state, txt])
clear.click(bot.memory.clear)
clear.click(lambda: [], None, chatbot)
clear.click(lambda: [], None, state)
demo.launch(server_name="0.0.0.0", server_port=7861)
gitextract_kp4_0mc4/ ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.txt ├── LowCodeLLM/ │ ├── Dockerfile │ ├── README.md │ ├── config.template │ └── src/ │ ├── app.py │ ├── executingLLM.py │ ├── index.html │ ├── lowCodeLLM.py │ ├── openAIWrapper.py │ ├── planningLLM.py │ ├── requirements.txt │ ├── supervisord.conf │ └── test/ │ ├── test_execute.py │ ├── test_extend_workflow.py │ ├── test_get_workflow.py │ └── testcases/ │ ├── execute_test_cases.json │ ├── extend_workflow_test_cases.json │ └── get_workflow_test_cases.json ├── README.md ├── SECURITY.md ├── TaskMatrix.AI/ │ └── README.md ├── requirements.txt └── visual_chatgpt.py
SYMBOL INDEX (138 symbols across 9 files)
FILE: LowCodeLLM/src/app.py
function index (line 21) | def index():
function get_workflow (line 26) | def get_workflow():
function extend_workflow (line 39) | def extend_workflow():
function execute (line 54) | def execute():
FILE: LowCodeLLM/src/executingLLM.py
class executingLLM (line 26) | class executingLLM:
method __init__ (line 27) | def __init__(self, temperature) -> None:
method execute (line 34) | def execute(self, current_prompt, history):
FILE: LowCodeLLM/src/lowCodeLLM.py
class lowCodeLLM (line 8) | class lowCodeLLM:
method __init__ (line 9) | def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):
method get_workflow (line 13) | def get_workflow(self, task_prompt):
method extend_workflow (line 16) | def extend_workflow(self, task_prompt, current_workflow, step=''):
method execute (line 23) | def execute(self, task_prompt,confirmed_workflow, history, curr_input):
method _json2txt (line 31) | def _json2txt(self, workflow_json):
FILE: LowCodeLLM/src/openAIWrapper.py
class OpenAIWrapper (line 7) | class OpenAIWrapper:
method __init__ (line 8) | def __init__(self, temperature):
method run (line 37) | def run(self, prompt):
method _post_request_chat (line 40) | def _post_request_chat(self, messages):
FILE: LowCodeLLM/src/planningLLM.py
class planningLLM (line 46) | class planningLLM:
method __init__ (line 47) | def __init__(self, temperature) -> None:
method get_workflow (line 53) | def get_workflow(self, task_prompt):
method extend_workflow (line 65) | def extend_workflow(self, task_prompt, current_workflow, step):
method _txt2json (line 77) | def _txt2json(self, workflow_txt):
FILE: LowCodeLLM/src/test/test_execute.py
function test_extend_workflow (line 10) | def test_extend_workflow():
FILE: LowCodeLLM/src/test/test_extend_workflow.py
function test_extend_workflow (line 10) | def test_extend_workflow():
FILE: LowCodeLLM/src/test/test_get_workflow.py
function test_get_workflow (line 9) | def test_get_workflow():
FILE: visual_chatgpt.py
function seed_everything (line 141) | def seed_everything(seed):
function prompts (line 149) | def prompts(name, description):
function blend_gt2pt (line 158) | def blend_gt2pt(old_image, new_image, sigma=0.15, steps=100):
function cut_dialogue_history (line 215) | def cut_dialogue_history(history_memory, keep_last_n_words=500):
function get_new_image_name (line 231) | def get_new_image_name(org_img_name, func_name="update"):
class InstructPix2Pix (line 246) | class InstructPix2Pix:
method __init__ (line 247) | def __init__(self, device):
method inference (line 262) | def inference(self, inputs):
class Text2Image (line 275) | class Text2Image:
method __init__ (line 276) | def __init__(self, device):
method inference (line 291) | def inference(self, text):
class ImageCaptioning (line 301) | class ImageCaptioning:
method __init__ (line 302) | def __init__(self, device):
method inference (line 313) | def inference(self, image_path):
class Image2Canny (line 321) | class Image2Canny:
method __init__ (line 322) | def __init__(self, device):
method inference (line 332) | def inference(self, inputs):
class CannyText2Image (line 345) | class CannyText2Image:
method __init__ (line 346) | def __init__(self, device):
method inference (line 367) | def inference(self, inputs):
class Image2Line (line 382) | class Image2Line:
method __init__ (line 383) | def __init__(self, device):
method inference (line 392) | def inference(self, inputs):
class LineText2Image (line 401) | class LineText2Image:
method __init__ (line 402) | def __init__(self, device):
method inference (line 425) | def inference(self, inputs):
class Image2Hed (line 440) | class Image2Hed:
method __init__ (line 441) | def __init__(self, device):
method inference (line 450) | def inference(self, inputs):
class HedText2Image (line 459) | class HedText2Image:
method __init__ (line 460) | def __init__(self, device):
method inference (line 483) | def inference(self, inputs):
class Image2Scribble (line 498) | class Image2Scribble:
method __init__ (line 499) | def __init__(self, device):
method inference (line 508) | def inference(self, inputs):
class ScribbleText2Image (line 517) | class ScribbleText2Image:
method __init__ (line 518) | def __init__(self, device):
method inference (line 539) | def inference(self, inputs):
class Image2Pose (line 554) | class Image2Pose:
method __init__ (line 555) | def __init__(self, device):
method inference (line 563) | def inference(self, inputs):
class PoseText2Image (line 572) | class PoseText2Image:
method __init__ (line 573) | def __init__(self, device):
method inference (line 597) | def inference(self, inputs):
class SegText2Image (line 611) | class SegText2Image:
method __init__ (line 612) | def __init__(self, device):
method inference (line 633) | def inference(self, inputs):
class Image2Depth (line 648) | class Image2Depth:
method __init__ (line 649) | def __init__(self, device):
method inference (line 657) | def inference(self, inputs):
class DepthText2Image (line 670) | class DepthText2Image:
method __init__ (line 671) | def __init__(self, device):
method inference (line 692) | def inference(self, inputs):
class Image2Normal (line 707) | class Image2Normal:
method __init__ (line 708) | def __init__(self, device):
method inference (line 717) | def inference(self, inputs):
class NormalText2Image (line 741) | class NormalText2Image:
method __init__ (line 742) | def __init__(self, device):
method inference (line 763) | def inference(self, inputs):
class VisualQuestionAnswering (line 778) | class VisualQuestionAnswering:
method __init__ (line 779) | def __init__(self, device):
method inference (line 791) | def inference(self, inputs):
class Segmenting (line 802) | class Segmenting:
method __init__ (line 803) | def __init__(self, device):
method download_parameters (line 817) | def download_parameters(self):
method show_mask (line 823) | def show_mask(self, mask: np.ndarray,image: np.ndarray,
method show_box (line 849) | def show_box(self, box, ax, label):
method get_mask_with_boxes (line 856) | def get_mask_with_boxes(self, image_pil, image, boxes_filt):
method segment_image_with_boxes (line 876) | def segment_image_with_boxes(self, image_pil, image_path, boxes_filt, ...
method set_image (line 896) | def set_image(self, img) -> None:
method show_points (line 901) | def show_points(self, coords: np.ndarray, labels: np.ndarray,
method segment_image_with_click (line 924) | def segment_image_with_click(self, img, is_positive: bool,
method segment_image_with_coordinate (line 947) | def segment_image_with_coordinate(self, img, is_positive: bool,
method inference_all (line 997) | def inference_all(self,image_path):
class Text2Box (line 1026) | class Text2Box:
method __init__ (line 1027) | def __init__(self, device):
method download_parameters (line 1038) | def download_parameters(self):
method load_image (line 1045) | def load_image(self,image_path):
method load_model (line 1059) | def load_model(self):
method get_grounding_boxes (line 1069) | def get_grounding_boxes(self, image, caption, with_logits=True):
method plot_boxes_to_image (line 1103) | def plot_boxes_to_image(self, image_pil, tgt):
method inference (line 1147) | def inference(self, inputs):
class Inpainting (line 1171) | class Inpainting:
method __init__ (line 1172) | def __init__(self, device):
method __call__ (line 1179) | def __call__(self, prompt, image, mask_image, height=512, width=512, n...
class InfinityOutPainting (line 1184) | class InfinityOutPainting:
method __init__ (line 1186) | def __init__(self, ImageCaptioning, Inpainting, VisualQuestionAnswering):
method get_BLIP_vqa (line 1195) | def get_BLIP_vqa(self, image, question):
method get_BLIP_caption (line 1203) | def get_BLIP_caption(self, image):
method check_prompt (line 1210) | def check_prompt(self, prompt):
method get_imagine_caption (line 1216) | def get_imagine_caption(self, image, imagine):
method resize_image (line 1233) | def resize_image(self, image, max_size=1000000, multiple=8):
method dowhile (line 1240) | def dowhile(self, original_img, tosize, expand_ratio, imagine, usr_pro...
method inference (line 1268) | def inference(self, inputs):
class ObjectSegmenting (line 1283) | class ObjectSegmenting:
method __init__ (line 1285) | def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting):
method inference (line 1298) | def inference(self, inputs):
method merge_masks (line 1310) | def merge_masks(self, masks):
method get_mask (line 1329) | def get_mask(self, image_path, text_prompt):
class ImageEditing (line 1357) | class ImageEditing:
method __init__ (line 1359) | def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting, Inpaintin...
method pad_edge (line 1365) | def pad_edge(self,mask,padding):
method inference_remove (line 1382) | def inference_remove(self, inputs):
method inference_replace_sam (line 1391) | def inference_replace_sam(self,inputs):
class BackgroundRemoving (line 1418) | class BackgroundRemoving:
method __init__ (line 1423) | def __init__(self,VisualQuestionAnswering:VisualQuestionAnswering, Tex...
method inference (line 1431) | def inference(self, image_path):
method get_mask (line 1448) | def get_mask(self, image_path):
class ConversationBot (line 1465) | class ConversationBot:
method __init__ (line 1466) | def __init__(self, load_dict):
method init_agent (line 1497) | def init_agent(self, lang):
method run_text (line 1518) | def run_text(self, text, state):
method run_image (line 1528) | def run_image(self, image, state, txt, lang):
Condensed preview — 25 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (158K chars).
[
{
"path": "CODE_OF_CONDUCT.md",
"chars": 443,
"preview": "# Microsoft Open Source Code of Conduct\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://op"
},
{
"path": "CONTRIBUTING.md",
"chars": 1704,
"preview": "\nTo contribute to this GitHub project, you can follow these steps:\n\n1. Fork the repository you want to contribute to by "
},
{
"path": "LICENSE.txt",
"chars": 1953,
"preview": "MIT License\n\nCopyright (c) 2023 Microsoft\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n"
},
{
"path": "LowCodeLLM/Dockerfile",
"chars": 396,
"preview": "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 insta"
},
{
"path": "LowCodeLLM/README.md",
"chars": 4164,
"preview": "# Low-code LLM\n\n**Low-code LLM** is a novel human-LLM interaction pattern, involving human in the loop to achieve more c"
},
{
"path": "LowCodeLLM/config.template",
"chars": 153,
"preview": "USE_AZURE=True\r\nOPENAIKEY=your-azure-openai-service-key\r\nAPI_BASE=your-base-url-for-azure\r\nAPI_VERSION=2023-03-15-previe"
},
{
"path": "LowCodeLLM/src/app.py",
"chars": 2493,
"preview": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport os\r\nfrom flask import Flask, request"
},
{
"path": "LowCodeLLM/src/executingLLM.py",
"chars": 1988,
"preview": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nfrom openAIWrapper import OpenAIWrapper\r\n\r\n"
},
{
"path": "LowCodeLLM/src/index.html",
"chars": 22957,
"preview": "<!-- Copyright (c) Microsoft Corporation.\r\n Licensed under the MIT License. -->\r\n \r\n<!DOCTYPE html>\r\n<html lang="
},
{
"path": "LowCodeLLM/src/lowCodeLLM.py",
"chars": 2021,
"preview": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nfrom planningLLM import planningLLM\r\nfrom e"
},
{
"path": "LowCodeLLM/src/openAIWrapper.py",
"chars": 2180,
"preview": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport os\r\nimport openai\r\n\r\nclass OpenAIWra"
},
{
"path": "LowCodeLLM/src/planningLLM.py",
"chars": 5657,
"preview": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport re\r\nimport json\r\nfrom openAIWrapper "
},
{
"path": "LowCodeLLM/src/requirements.txt",
"chars": 84,
"preview": "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",
"chars": 325,
"preview": "[supervisord]\r\nnodaemon=true\r\nloglevel=info\r\n\r\n[program:flask]\r\ncommand=gunicorn --timeout 300 --bind \"0.0.0.0:8888\" \"ap"
},
{
"path": "LowCodeLLM/src/test/test_execute.py",
"chars": 692,
"preview": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport json\r\nimport sys\r\nimport os\r\nimport "
},
{
"path": "LowCodeLLM/src/test/test_extend_workflow.py",
"chars": 620,
"preview": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport json\r\nimport sys\r\nimport os\r\nimport "
},
{
"path": "LowCodeLLM/src/test/test_get_workflow.py",
"chars": 475,
"preview": "# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n\r\nimport json\r\nimport sys\r\nimport os\r\nsys.pat"
},
{
"path": "LowCodeLLM/src/test/testcases/execute_test_cases.json",
"chars": 3941,
"preview": "[\r\n {\r\n \"task_prompt\": \"Write an essay about drunk driving issue.\",\r\n \"confirmed_workflow\": \"[{\\\"stepId"
},
{
"path": "LowCodeLLM/src/test/testcases/extend_workflow_test_cases.json",
"chars": 3705,
"preview": "[\r\n {\r\n \"task_prompt\": \"Write an essay about drunk driving issue.\",\r\n \"current_workflow\": \"[{\\\"stepId\\\""
},
{
"path": "LowCodeLLM/src/test/testcases/get_workflow_test_cases.json",
"chars": 241,
"preview": "[\r\n {\r\n \"task_prompt\": \"Write an essay about drunk driving issue.\"\r\n },\r\n {\r\n \"task_prompt\": \"Wri"
},
{
"path": "README.md",
"chars": 8745,
"preview": "# TaskMatrix\n\n**TaskMatrix** connects ChatGPT and a series of Visual Foundation Models to enable **sending** and **recei"
},
{
"path": "SECURITY.md",
"chars": 2756,
"preview": "<!-- BEGIN MICROSOFT SECURITY.MD V0.0.7 BLOCK -->\n\n## Security\n\nMicrosoft takes the security of our software products an"
},
{
"path": "TaskMatrix.AI/README.md",
"chars": 861,
"preview": "## Description\n**TaskMatrix.AI** is an AI ecosystem that can connect foundation models with millions of APIs for task co"
},
{
"path": "requirements.txt",
"chars": 337,
"preview": "langchain==0.0.101\ntorch==1.13.1\ntorchvision==0.14.1\nwget==3.2\naccelerate\naddict\nalbumentations\nbasicsr\ncontrolnet-aux\nd"
},
{
"path": "visual_chatgpt.py",
"chars": 79428,
"preview": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n# coding: utf-8\nimport os\nimport gradio as gr\n"
}
]
About this extraction
This page contains the full source code of the microsoft/TaskMatrix GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 25 files (144.8 KB), approximately 35.0k tokens, and a symbol index with 138 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.