xrngen-cli 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #!/usr/bin/env python3
  2. '''
  3. Software License
  4. Copyright (C) 2021-05-24 Xoronos
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, version 3.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. '''
  15. '''
  16. Liabilities
  17. The software is provided "AS IS" without any warranty of any kind, either expressed,
  18. implied, or statutory, including, but not limited to, any warranty that the software
  19. will conform to specifications, any implied warranties of merchantability, fitness
  20. for a particular purpose, and freedom from infringement, and any warranty that the
  21. documentation will conform to the software, or any warranty that the software will
  22. be error free.
  23. In no event shall Xoronos be liable for any damages, including, but not limited to,
  24. direct, indirect, special or consequential damages, arising out of, resulting from,
  25. or in any way connected with this software, whether or not based upon warranty,
  26. contract, tort, or otherwise, whether or not injury was sustained by persons or
  27. property or otherwise, and whether or not loss was sustained from, or arose out of
  28. the results of, or use of, the software or services provided hereunder.
  29. To request the provided software under a different license you can contact us at
  30. support@xoronos.com
  31. '''
  32. import argparse
  33. import argparse
  34. import random
  35. import re
  36. import requests
  37. import json
  38. import os
  39. folder = "./gen/"
  40. size = "256x256"
  41. localai_server_image = "http://localhost:8080/v1/images/generations"
  42. localai_server_chat = "http://localhost:8080/v1/chat/completions"
  43. localai_server_t2s = 'http://localhost:8080/tts'
  44. # This is the default implementation with localai
  45. # for implementing a different service you can reimplement gen, get_names, flush ,delete_all
  46. class XRN_gen_text:
  47. #def __init__(self):
  48. def gen(self,prompt):
  49. self.headers = {
  50. "Content-Type": "application/json"
  51. }
  52. self.json_data = {
  53. "model": "gpt-4",
  54. "messages": [{"role": "user", "content": prompt }]
  55. }
  56. response = requests.post(localai_server_chat, headers=self.headers, data=json.dumps(self.json_data))
  57. if response.status_code == 200 :
  58. t = json.loads(response.text)
  59. for choiche in t['choices'] :
  60. return choiche["message"]["content"]
  61. else:
  62. print("responce not valid ")
  63. print(response.text) # Print the content of the response
  64. return -1
  65. return 0
  66. # This is the default implementation with localai
  67. # for implementing a different service you can reimplement gen, get_names, flush ,delete_all
  68. class XRN_gen_image:
  69. def __init__(self):
  70. self.files= []
  71. def gen(self,prompt,fwpath=""):
  72. self.headers = {
  73. "Content-Type": "application/json"
  74. }
  75. self.json_data = {
  76. "prompt": prompt,
  77. "size": size
  78. }
  79. response = requests.post(localai_server_image, headers=self.headers, data=json.dumps(self.json_data))
  80. if response.status_code == 200 :
  81. t = json.loads(response.text)
  82. for a in t['data'] :
  83. print (a['url'])
  84. image_url = a['url']
  85. splitteturl = image_url.split("/")
  86. for x in splitteturl:
  87. lastname = x
  88. #print(lastname)
  89. self.files.append(lastname)
  90. try:
  91. response = requests.get(image_url)
  92. response.raise_for_status() # Check if the request was successful
  93. if fwpath == "":
  94. fwpath = folder+lastname
  95. with open(fwpath, 'wb') as file:
  96. file.write(response.content)
  97. except Exception as err:
  98. print(f' error occurred: {err}') # Print any other error
  99. return -2
  100. else:
  101. print("responce not valid ")
  102. print(response.text) # Print the content of the response
  103. return False
  104. return True
  105. def get_names(self):
  106. return self.files
  107. def flush(self):
  108. self.files = []
  109. def delete_all(self):
  110. for n in self.files:
  111. os.remove(folder+n)
  112. class XRN_gen_audio:
  113. def __init__(self):
  114. self.files= []
  115. random.seed(version=2)
  116. self.name = random.randbytes(8).hex()
  117. self.audiocount = 0
  118. def gen(self,prompt,filename=None):
  119. self.headers = {
  120. "Content-Type": "application/json"
  121. }
  122. self.json_data = {
  123. "backend": "auto",
  124. "model": "tts-1",
  125. "input": prompt
  126. }
  127. try:
  128. response = requests.post(localai_server_t2s, headers=self.headers, data=json.dumps(self.json_data))
  129. response.raise_for_status() # Check if the request was successful
  130. if filename == None :
  131. filename = folder+self.name+str(self.audiocount)+".wav"
  132. with open( filename, 'wb') as file:
  133. file.write(response.content)
  134. self.files.append(filename)
  135. self.audiocount += 1
  136. except Exception as err:
  137. print(f'Other error occurred: {err}') # Print any other error
  138. return False
  139. return True
  140. def get_names(self):
  141. return self.files
  142. def flush(self):
  143. self.files = []
  144. def delete_all(self):
  145. for n in self.files:
  146. os.remove(folder+n)
  147. concat_N = 4
  148. def main():
  149. parser = argparse.ArgumentParser(
  150. description="Utility for generating content",
  151. usage="""%(prog)s [--text2image [-prompt "string" | -auto-prompt ] -size WITHxHEIGH -image /path/to/image.png ] [--text2speach [ -prompt "string" | -auto-prompt ] -audio /path/to/audio.flac ]
  152. Examples:
  153. """
  154. )
  155. # Adding arguments for --text2speach
  156. parser.add_argument('--text2speach', action='store_true', help="Text to speech command")
  157. parser.add_argument('-audio', type=str, help="First argument for text2speach (mandatory if --text2speach is used)")
  158. # Adding arguments for --text2image
  159. parser.add_argument('--text2image', action='store_true', help="Text to image command")
  160. parser.add_argument('-size', type=str,nargs=1,help="Size of image WITHxHEIGH")
  161. parser.add_argument('-image', type=str,nargs=1, help="Third argument for text2image (mandatory if --text2image is used)")
  162. # Adding mutually exclusive arguments
  163. exclusive_group = parser.add_mutually_exclusive_group()
  164. exclusive_group.add_argument('-prompt', help='the prompt to send ',type=str,nargs=1)
  165. exclusive_group.add_argument('-auto-prompt', action='store_true', help='autogenerate prompt')
  166. # Parsing arguments
  167. args = parser.parse_args()
  168. # Handling arguments
  169. if args.text2speach:
  170. if not check_prompt(args) :
  171. parser.print_help()
  172. else :
  173. if args.audio:
  174. handle_text2speach(args)
  175. else:
  176. print("Error: --text2speach requires -audio.")
  177. parser.print_usage()
  178. elif args.text2image:
  179. pattern = r'^\d+(x|X)\d+$'
  180. if not check_prompt(args) :
  181. parser.print_help()
  182. else :
  183. if args.size and args.image :
  184. match = bool(re.match(pattern, args.size[0]))
  185. if match :
  186. handle_text2image(args)
  187. else:
  188. print("Error: -size argument sintax wrong ")
  189. parser.print_usage()
  190. else:
  191. print("Error: -image requires -size and -image")
  192. parser.print_usage()
  193. else:
  194. parser.print_help()
  195. def check_prompt(args):
  196. if args.prompt or args.auto_prompt :
  197. if args.prompt and args.auto_prompt :
  198. print("Error: only one between -prompt and -auto-prompt can be used")
  199. return False
  200. return True
  201. else :
  202. print("Error: -prompt or -auto-prompt is required")
  203. return False
  204. def gen_auto_prompt():
  205. print("auto_prompt could be very slow, if you want to speedup it is possible to use -prompt \"Prompt sentence \" ")
  206. auto_prompt_list = []
  207. with open("code/autoprompt.txt","r") as file:
  208. line_count = 0
  209. for line in file:
  210. #print(line)
  211. # Increment the line count
  212. line_count += 1
  213. # Print the current line
  214. auto_prompt_list.append(line)
  215. #print(line_count)
  216. auto_prompt = ""
  217. for i in range(0,concat_N) :
  218. auto_prompt += auto_prompt_list[random.randint(0, line_count-1)]
  219. auto_prompt = auto_prompt.replace('\n', ' ')
  220. #print(auto_prompt)
  221. x = XRN_gen_text()
  222. return x.gen(auto_prompt)
  223. def handle_text2speach(args):
  224. if args.auto_prompt:
  225. prompt = gen_auto_prompt()
  226. else :
  227. prompt = args.prompt[0]
  228. print(prompt)
  229. x = XRN_gen_audio()
  230. x.gen(prompt)
  231. def handle_text2image(args):
  232. if args.auto_prompt:
  233. prompt = gen_auto_prompt()
  234. else :
  235. prompt = args.prompt[0]
  236. x = XRN_gen_image()
  237. x.gen(prompt,args.image[0])
  238. if __name__ == "__main__":
  239. main()