pycoze 0.1.218__tar.gz → 0.1.221__tar.gz

Sign up to get free protection for your applications and to get access to all the features.
Files changed (42) hide show
  1. {pycoze-0.1.218 → pycoze-0.1.221}/PKG-INFO +1 -1
  2. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/ai/__init__.py +1 -0
  3. pycoze-0.1.221/pycoze/ai/llm/__init__.py +2 -0
  4. pycoze-0.1.221/pycoze/ai/llm/text_to_image_prompt.py +66 -0
  5. pycoze-0.1.221/pycoze/ai/llm/think.py +131 -0
  6. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/bot/agent_chat.py +2 -0
  7. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/ui/ui_def.py +5 -7
  8. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze.egg-info/PKG-INFO +1 -1
  9. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze.egg-info/SOURCES.txt +3 -0
  10. {pycoze-0.1.218 → pycoze-0.1.221}/setup.py +1 -1
  11. {pycoze-0.1.218 → pycoze-0.1.221}/LICENSE +0 -0
  12. {pycoze-0.1.218 → pycoze-0.1.221}/README.md +0 -0
  13. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/__init__.py +0 -0
  14. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/ai/vram_reserve.py +0 -0
  15. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/automation/__init__.py +0 -0
  16. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/automation/browser/__init__.py +0 -0
  17. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/automation/browser/edge_driver_manager.py +0 -0
  18. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/bot/__init__.py +0 -0
  19. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/bot/agent/__init__.py +0 -0
  20. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/bot/agent/agent.py +0 -0
  21. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/bot/agent/agent_types/__init__.py +0 -0
  22. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/bot/agent/agent_types/const.py +0 -0
  23. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/bot/agent/agent_types/openai_func_call_agent.py +0 -0
  24. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/bot/agent/assistant.py +0 -0
  25. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/bot/agent/chat.py +0 -0
  26. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/bot/bot.py +0 -0
  27. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/reference/__init__.py +0 -0
  28. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/reference/bot.py +0 -0
  29. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/reference/lib.py +0 -0
  30. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/reference/tool.py +0 -0
  31. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/reference/workflow.py +0 -0
  32. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/ui/__init__.py +0 -0
  33. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/ui/base.py +0 -0
  34. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/ui/color.py +0 -0
  35. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/ui/typ.py +0 -0
  36. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/utils/__init__.py +0 -0
  37. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/utils/arg.py +0 -0
  38. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/utils/env.py +0 -0
  39. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze/utils/text_or_file.py +0 -0
  40. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze.egg-info/dependency_links.txt +0 -0
  41. {pycoze-0.1.218 → pycoze-0.1.221}/pycoze.egg-info/top_level.txt +0 -0
  42. {pycoze-0.1.218 → pycoze-0.1.221}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pycoze
3
- Version: 0.1.218
3
+ Version: 0.1.221
4
4
  Summary: Package for pycoze only!
5
5
  Author: Yuan Jie Xiong
6
6
  Author-email: aiqqqqqqq@qq.com
@@ -1 +1,2 @@
1
1
  from .vram_reserve import reserve_vram, reserve_vram_retry, unreserve_vram
2
+ from .llm import think, think_stream, extract, yes_or_no, extract_code
@@ -0,0 +1,2 @@
1
+ from .text_to_image_prompt import text_to_image_prompt
2
+ from .think import think, think_stream, extract, yes_or_no, extract_code
@@ -0,0 +1,66 @@
1
+ import re
2
+ from .. import yes_or_no
3
+ from .. import extract
4
+
5
+
6
+ def contains_chinese(text):
7
+ pattern = re.compile(r'[\u4e00-\u9fa5]') # Regular expression to match Chinese characters
8
+ return bool(re.search(pattern, text))
9
+
10
+
11
+ requirement = """
12
+ Please reflect the scene content as prompts for the drawing AI.
13
+
14
+ ## Prompt Concept
15
+ - A prompt is used to describe the image content, composed of common words, using English commas (",") as separators. For example, a prompt like "woman" indicates that the image should include a woman.
16
+
17
+ ## Tag Restrictions
18
+ - Tags should be described using English words or phrases, avoiding Chinese.
19
+ - Tags can only contain keywords or key phrases, and should not include personal names, place names, etc.
20
+ - Tags should try to preserve physical characteristics of people, like body shape and hairstyle, but not use personal names, instead using terms like "man" to refer to people.
21
+ - The number of tags in a prompt is limited to 40, and the number of words is limited to 60.
22
+
23
+ ## Incorrect Examples of Prompts
24
+ "In the bustling Shanghai Bund, there is a young man named Li Yang."
25
+ The prompt includes non-keywords like "there is", as well as the personal name "Li Yang" and the place name "Shanghai."
26
+ It should be modified to "a young man, in the bustling Bund"
27
+
28
+ """
29
+
30
+ # As the LLM used is not very effective, negative prompts are not suitable for generation by LLM at this stage
31
+ # - Negative prompts describe content that should not appear in the image, for example if "bird, man" appears in the negative prompt, it means the image should not include "birds and men".
32
+
33
+
34
+ def text_to_image_prompt(query, style, negative_style, with_prompt="best quality,4k,", with_negative_prompt=""):
35
+ query = query.replace("{", "【").replace("}", "】")
36
+ needed = f"The scene I need: {query}"
37
+ style = style.replace(",", " ").replace(",", " ")
38
+ if len(style) > 0:
39
+ needed += f"\nThe style I need: {style}"
40
+ # if len(negative_style) > 0:
41
+ # needed += f"\nStyles to avoid: {negative_style}"
42
+
43
+ for i in range(15):
44
+ try:
45
+ print("doing")
46
+ output_obj = extract([("prompt", "Describe the image content with keywords")], needed + "\n" + requirement)
47
+ print("done")
48
+ if contains_chinese(output_obj["prompt"]):
49
+ print("Contains Chinese, regenerating")
50
+ continue
51
+ if yes_or_no("Does it include personal names:\n"+output_obj["prompt"]):
52
+ print(output_obj["prompt"]+" contains personal names, correcting")
53
+ output_obj["prompt"] = extract(
54
+ [("text without personal names", "Modified result (personal names can be changed to man, woman, he, she, etc.)")],
55
+ "Modify the following text, personal names can be changed to man, woman, he, she, etc.: \n"+output_obj["prompt"])["text without personal names"]
56
+ break
57
+ except Exception as e:
58
+ print(e)
59
+ output_obj["prompt"] = with_prompt + output_obj["prompt"].replace(" and ", ",")
60
+ output_obj["negative_prompt"] = with_negative_prompt
61
+ output_obj["with_prompt"] = with_prompt
62
+ output_obj["with_negative_prompt"] = with_negative_prompt
63
+ output_obj["query"] = query
64
+ output_obj["style"] = style
65
+ output_obj["negative_style"] = negative_style
66
+ return output_obj
@@ -0,0 +1,131 @@
1
+ from pycoze import utils
2
+ import json5
3
+ import re
4
+ from retrying import retry
5
+ from openai import OpenAI
6
+ import openai
7
+ import requests
8
+ import os
9
+
10
+
11
+ def never_retry_on_rate_limit_error(exception):
12
+ """Return True if we should retry (in this case when it's NOT a RateLimitError), False otherwise"""
13
+ return not isinstance(exception, openai.RateLimitError)
14
+
15
+ @retry(retry_on_exception=never_retry_on_rate_limit_error, wait_exponential_multiplier=500, stop_max_attempt_number=5)
16
+ def think(user_text, history, temperature=0.2, stop=None, **kwargs):
17
+ user_msg = {"role": "user", "content": user_text}
18
+ cfg = utils.read_json_file("llm.json")
19
+
20
+ base_url = cfg["baseURL"]
21
+ api_key = cfg["apiKey"]
22
+ model = cfg["model"]
23
+
24
+ base_url = base_url.replace("/chat/completions", "")
25
+
26
+ client = OpenAI(api_key=api_key, base_url=base_url)
27
+
28
+ response = client.chat.completions.create(model=model,
29
+ messages=simple_history(history) + [user_msg],
30
+ temperature=temperature,
31
+ stop=stop)
32
+ return response.choices[0].message.content
33
+
34
+
35
+ @retry(retry_on_exception=never_retry_on_rate_limit_error, wait_exponential_multiplier=500, stop_max_attempt_number=5)
36
+ def think_stream(user_text, history, temperature=0.2, stop=None, **kwargs):
37
+ user_msg = {"role": "user", "content": user_text}
38
+ cfg = utils.read_json_file("llm.json")
39
+
40
+ base_url = cfg["baseURL"]
41
+ api_key = cfg["apiKey"]
42
+ model = cfg["model"]
43
+
44
+ base_url = base_url.replace("/chat/completions", "")
45
+
46
+ client = OpenAI(api_key=api_key, base_url=base_url)
47
+
48
+
49
+ stream = client.chat.completions.create(model=model,
50
+ messages=simple_history(history) + [user_msg],
51
+ stream=True,
52
+ temperature=temperature,
53
+ stop=stop)
54
+ for chunk in stream:
55
+ yield chunk.choices[0].delta.content or ""
56
+
57
+
58
+ def simple_history(history):
59
+ return [{"role": h["role"], "content": h["content"]} for h in history]
60
+
61
+
62
+ @retry(retry_on_exception=never_retry_on_rate_limit_error, wait_exponential_multiplier=500, stop_max_attempt_number=3)
63
+ def extract(response_data, text: str, temperature=0, **kwargs):
64
+ """print(extract({"name": "lowercase"}, "hello XiaoMing"))"""
65
+ if isinstance(response_data, dict):
66
+ response_items = [[res, response_data[res]] for res in response_data]
67
+ else:
68
+ response_items = response_data
69
+
70
+ json_text = ""
71
+ for i, res in enumerate(response_items):
72
+ comma = "," if i != len(response_items) - 1 else ""
73
+ json_text += f' "{res[0]}": {res[1]}{comma}\n'
74
+
75
+ # Combine the provided text with the formatted JSON schema
76
+ think_text = f"""
77
+ The output should be a markdown code snippet formatted in the following schema, including the leading and trailing "```json" and "```" tags:
78
+ ```json
79
+ {{
80
+ {json_text}
81
+ }}
82
+ ```
83
+
84
+ Request:
85
+ {text}
86
+ """
87
+ # text放后面,当翻译等情况时,不会把"The output should"之类翻译了,导致错误
88
+ markdown = think(think_text, [], temperature=temperature, **kwargs)
89
+ pattern = r'```json(.*?)```'
90
+ matches = re.findall(pattern, markdown, re.DOTALL)
91
+ if matches:
92
+ json_str = matches[0].strip()
93
+ # lines = [line.split("//")[0] for line in json_str.split("\n")]//这样当json中有//时会出错,例如https://
94
+ json_dict = json5.loads(json_str)
95
+ for item in response_items:
96
+ if item[0] not in json_dict:
97
+ raise "item:" + item + " not exists"
98
+ return json_dict
99
+
100
+
101
+ def yes_or_no(question, temperature=0, **kwargs):
102
+ result = extract([("Result", "Yes or No")], question,
103
+ temperature=temperature, **kwargs)["Result"]
104
+ if isinstance(result, bool):
105
+ return result
106
+ return result.upper() == "YES"
107
+
108
+
109
+ @retry(retry_on_exception=never_retry_on_rate_limit_error, wait_exponential_multiplier=500, stop_max_attempt_number=3)
110
+ def extract_code(text: str, temperature=0, language="python", markdown_word='python', **kwargs):
111
+ """print(extract_code("sum 1~100"))"""
112
+ think_text = text + f"""
113
+ The output should be a complete and usable {language} code snippet, including the leading and trailing "```{markdown_word}" and "```":
114
+ """
115
+ markdown = think(think_text, [], temperature=temperature, **kwargs)
116
+ # 使用正则表达式匹配围绕在```{markdown_word} 和 ```之间的文本
117
+ pattern = rf'```{markdown_word}(.*?)```'
118
+ matches = re.findall(pattern, markdown, re.DOTALL)
119
+ if matches:
120
+ # 去除可能的前后空白字符
121
+ return matches[0].strip()
122
+ else:
123
+ raise Exception("The string is not a valid python code.")
124
+
125
+
126
+ if __name__ == "__main__":
127
+ print(lib_think("你好", []))
128
+ for chunk in lib_think_stream("你好", []):
129
+ print(chunk)
130
+ print(extract({"name": "lowercase"}, "hello XiaoMing"))
131
+ print(extract_code("sum 1~100"))
@@ -10,6 +10,8 @@ from langchain_core.utils.function_calling import convert_to_openai_tool
10
10
  import os
11
11
 
12
12
  cfg = utils.read_json_file("llm.json")
13
+ if cfg["model"].startswith("qwen-"):
14
+ cfg["toolCompatibilityMode"] = False
13
15
 
14
16
 
15
17
  def load_role_setting(bot_setting_file: str):
@@ -185,13 +185,11 @@ def multi_video_select(
185
185
  def seed(name, default=0, tip="", hide_if="", style="", cls="") -> int:
186
186
  return useDefault(name, default)
187
187
 
188
+
188
189
  _cache_button_ui = get_ui()
189
- def button( name, tip="", hide_if="")->bool:
190
- value = useDefault(name, -1)
191
- if value is None: #value==None只会发生在在首次打开UI,后续每次运行都不会进入这里
192
- value = _cache_button_ui[name]
190
+ def button(name, tip="", hide_if="") -> bool:
191
+ value = useDefault(name, _cache_button_ui[name])
193
192
  if value != _cache_button_ui[name]:
194
- _cache_button_ui[name] = value # 更新last_value的值
193
+ _cache_button_ui[name] = value
195
194
  return True
196
- return False
197
-
195
+ return False
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pycoze
3
- Version: 0.1.218
3
+ Version: 0.1.221
4
4
  Summary: Package for pycoze only!
5
5
  Author: Yuan Jie Xiong
6
6
  Author-email: aiqqqqqqq@qq.com
@@ -8,6 +8,9 @@ pycoze.egg-info/dependency_links.txt
8
8
  pycoze.egg-info/top_level.txt
9
9
  pycoze/ai/__init__.py
10
10
  pycoze/ai/vram_reserve.py
11
+ pycoze/ai/llm/__init__.py
12
+ pycoze/ai/llm/text_to_image_prompt.py
13
+ pycoze/ai/llm/think.py
11
14
  pycoze/automation/__init__.py
12
15
  pycoze/automation/browser/__init__.py
13
16
  pycoze/automation/browser/edge_driver_manager.py
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="pycoze",
5
- version="0.1.218",
5
+ version="0.1.221",
6
6
  packages=find_packages(),
7
7
  install_requires=[],
8
8
  author="Yuan Jie Xiong",
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes