Compare commits

..

No commits in common. "e0107336d3859d0b87df3dac2c48131e164ae795" and "450c9ddb1b2a784c9685b40a6d31866a34d9126a" have entirely different histories.

2 changed files with 56 additions and 118 deletions

View File

@ -7,21 +7,8 @@ this is a txt2img bot to converse with SDweb bot [API](https://github.com/AUTOMA
supported invocation: supported invocation:
`/draw <text>` - send prompt text to the bot and it will draw an image `/draw <text>` - send prompt text to the bot and it will draw an image
you can add `negative_prompt` using `ng: <text>` you can add `negative_prompt` using `ng: <text>`
you can add `denoised intermediate steps` using `steps: <text>` you can add `denoised intermediate steps` using `steps: <text>`
basicly anything the `/controlnet/txt2img` API payload supports
like,
```json
{
"prompt": "",
"negative_prompt": "",
"denoising_strength": 0.5,
"seed": -1,
"n_iter": 1,
"steps": 20,
"cfg_scale": 7
}
```
examples: examples:
`/draw a city street` `/draw a city street`
and without people and without people

159
main.py
View File

@ -1,7 +1,6 @@
import json import json
import requests import requests
import io import io
import re
import os import os
import uuid import uuid
import base64 import base64
@ -27,97 +26,48 @@ SD_URL = os.environ.get("SD_URL", None)
print(SD_URL) print(SD_URL)
app = Client("stable", api_id=API_ID, api_hash=API_HASH, bot_token=TOKEN) app = Client("stable", api_id=API_ID, api_hash=API_HASH, bot_token=TOKEN)
# default params #default params
steps_value_default = 40 steps_value_default = 40
def process_input_string(string):
def parse_input(input_string): ng_delimiter = "ng:"
default_payload = { steps_delimiter = "steps:"
"prompt": "",
"negative_prompt": "", ng_index = string.find(ng_delimiter)
"controlnet_input_image": [], steps_index = string.find(steps_delimiter)
"controlnet_mask": [],
"controlnet_module": "", if ng_index != -1 and steps_index != -1:
"controlnet_model": "", if ng_index < steps_index:
"controlnet_weight": 1, positive = string[:ng_index].strip()
"controlnet_resize_mode": "Scale to Fit (Inner Fit)", negative = string[ng_index + len(ng_delimiter):steps_index].strip()
"controlnet_lowvram": False, steps_str = string[steps_index + len(steps_delimiter):].strip().split()[0]
"controlnet_processor_res": 64,
"controlnet_threshold_a": 64,
"controlnet_threshold_b": 64,
"controlnet_guidance": 1,
"controlnet_guessmode": True,
"enable_hr": False,
"denoising_strength": 0.5,
"hr_scale": 1.5,
"hr_upscale": "Latent",
"seed": -1,
"subseed": -1,
"subseed_strength": -1,
"sampler_index": "",
"batch_size": 1,
"n_iter": 1,
"steps": 20,
"cfg_scale": 7,
"width": 512,
"height": 512,
"restore_faces": True,
"override_settings": {},
"override_settings_restore_afterwards": True,
}
# Initialize an empty payload with the 'prompt' key
payload = {"prompt": ""}
prompt = []
# Find all occurrences of keys (words ending with a colon)
matches = re.finditer(r"(\w+):", input_string)
last_index = 0
# Iterate over the found keys
for match in matches:
key = match.group(1).lower() # Convert the key to lowercase
value_start_index = match.end()
# If there's text between the last key and the current key, add it to the prompt
if last_index != match.start():
prompt.append(input_string[last_index : match.start()].strip())
last_index = value_start_index
# Check if the key is in the default payload
if key in default_payload:
# Extract the value for the current key
value_end_index = re.search(
r"(?=\s+\w+:|$)", input_string[value_start_index:]
).start()
value = input_string[
value_start_index : value_start_index + value_end_index
].strip()
# Check if the default value for the key is an integer
if isinstance(default_payload[key], int):
# If the value is a valid integer, store it as an integer in the payload
if value.isdigit():
payload[key] = int(value)
else:
# If the default value for the key is not an integer, store the value as is in the payload
payload[key] = value
last_index += value_end_index
else: else:
# If the key is not in the default payload, add it to the prompt positive = string[:steps_index].strip()
prompt.append(f"{key}:") negative = string[steps_index + len(steps_delimiter):ng_index].strip()
steps_str = string[ng_index + len(ng_delimiter):].strip().split()[0]
elif ng_index != -1:
positive = string[:ng_index].strip()
negative = string[ng_index + len(ng_delimiter):].strip()
steps_str = None
elif steps_index != -1:
positive = string[:steps_index].strip()
negative = None
steps_str = string[steps_index + len(steps_delimiter):].strip().split()[0]
else:
positive = string.strip()
negative = None
steps_str = None
# Join the prompt words and store it in the payload try:
payload["prompt"] = " ".join(prompt) steps_value = int(steps_str)
#limit steps to range
# If the prompt is empty, set the input string as the prompt if not 1 <= steps_value <= 70:
if not payload["prompt"]: steps_value = steps_value_default
payload["prompt"] = input_string.strip() except (ValueError, TypeError):
steps_value = None
# Return the final payload
return payload
return positive, negative, steps_value
@app.on_message(filters.command(["draw"])) @app.on_message(filters.command(["draw"]))
def draw(client, message): def draw(client, message):
@ -128,11 +78,20 @@ def draw(client, message):
) )
return return
payload = parse_input(msgs[1]) positive, negative, steps_value = process_input_string(msgs[1])
payload = {
"prompt": positive,
}
if negative is not None:
payload["negative_prompt"] = negative
if steps_value is not None:
payload["steps"] = steps_value
print(payload) print(payload)
# The rest of the draw function remains unchanged # The rest of the draw function remains unchanged
K = message.reply_text("Please Wait 10-15 Second") K = message.reply_text("Please Wait 10-15 Second")
r = requests.post(url=f"{SD_URL}/sdapi/v1/txt2img", json=payload).json() r = requests.post(url=f"{SD_URL}/sdapi/v1/txt2img", json=payload).json()
@ -152,23 +111,15 @@ def draw(client, message):
pnginfo.add_text("parameters", response2.json().get("info")) pnginfo.add_text("parameters", response2.json().get("info"))
image.save(f"{word}.png", pnginfo=pnginfo) image.save(f"{word}.png", pnginfo=pnginfo)
# Add a flag to check if the user provided a seed value
user_provided_seed = "seed" in payload
info_dict = response2.json()
seed_value = info_dict['info'].split(", Seed: ")[1].split(",")[0]
# print(seed_value)
caption = f"**[{message.from_user.first_name}-Kun](tg://user?id={message.from_user.id})**\n\n"
for key, value in payload.items():
caption += f"{key.capitalize()} - **{value}**\n"
caption += f"Seed - **{seed_value}**\n"
message.reply_photo( message.reply_photo(
photo=f"{word}.png", photo=f"{word}.png",
caption=caption, caption=(
) f"Prompt - **{positive}**\n"
f"Negative Prompt - **{negative if negative is not None else 'None'}**\n"
f"Steps - **{steps_value if steps_value != steps_value_default else 'Default'}**\n"
f"**[{message.from_user.first_name}-Kun](tg://user?id={message.from_user.id})**"
),
)
# os.remove(f"{word}.png") # os.remove(f"{word}.png")
K.delete() K.delete()