123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309 |
- #!/usr/bin/env python3
- '''
- Software License
- Copyright (C) 2021-05-24 Xoronos
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, version 3.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <https://www.gnu.org/licenses/>.
- '''
- '''
- Liabilities
- The software is provided "AS IS" without any warranty of any kind, either expressed,
- implied, or statutory, including, but not limited to, any warranty that the software
- will conform to specifications, any implied warranties of merchantability, fitness
- for a particular purpose, and freedom from infringement, and any warranty that the
- documentation will conform to the software, or any warranty that the software will
- be error free.
- In no event shall Xoronos be liable for any damages, including, but not limited to,
- direct, indirect, special or consequential damages, arising out of, resulting from,
- or in any way connected with this software, whether or not based upon warranty,
- contract, tort, or otherwise, whether or not injury was sustained by persons or
- property or otherwise, and whether or not loss was sustained from, or arose out of
- the results of, or use of, the software or services provided hereunder.
-
- To request the provided software under a different license you can contact us at
- support@xoronos.com
- '''
- import argparse
- import argparse
- import random
- import re
- import requests
- import json
- import os
- folder = "./gen/"
- size = "256x256"
- localai_server_image = "http://localhost:8080/v1/images/generations"
- localai_server_chat = "http://localhost:8080/v1/chat/completions"
- localai_server_t2s = 'http://localhost:8080/tts'
- # This is the default implementation with localai
- # for implementing a different service you can reimplement gen, get_names, flush ,delete_all
- class XRN_gen_text:
- #def __init__(self):
-
-
- def gen(self,prompt):
- self.headers = {
- "Content-Type": "application/json"
- }
- self.json_data = {
- "model": "gpt-4",
- "messages": [{"role": "user", "content": prompt }]
- }
- response = requests.post(localai_server_chat, headers=self.headers, data=json.dumps(self.json_data))
-
- if response.status_code == 200 :
-
- t = json.loads(response.text)
- for choiche in t['choices'] :
- return choiche["message"]["content"]
- else:
- print("responce not valid ")
- print(response.text) # Print the content of the response
- return -1
- return 0
- # This is the default implementation with localai
- # for implementing a different service you can reimplement gen, get_names, flush ,delete_all
- class XRN_gen_image:
- def __init__(self):
-
- self.files= []
- def gen(self,prompt,fwpath=""):
- self.headers = {
- "Content-Type": "application/json"
- }
- self.json_data = {
- "prompt": prompt,
- "size": size
- }
- response = requests.post(localai_server_image, headers=self.headers, data=json.dumps(self.json_data))
-
- if response.status_code == 200 :
-
- t = json.loads(response.text)
- for a in t['data'] :
- print (a['url'])
- image_url = a['url']
- splitteturl = image_url.split("/")
- for x in splitteturl:
- lastname = x
- #print(lastname)
- self.files.append(lastname)
- try:
- response = requests.get(image_url)
- response.raise_for_status() # Check if the request was successful
- if fwpath == "":
- fwpath = folder+lastname
- with open(fwpath, 'wb') as file:
- file.write(response.content)
- except Exception as err:
- print(f' error occurred: {err}') # Print any other error
- return -2
- else:
- print("responce not valid ")
- print(response.text) # Print the content of the response
- return False
- return True
- def get_names(self):
- return self.files
- def flush(self):
- self.files = []
- def delete_all(self):
- for n in self.files:
- os.remove(folder+n)
- class XRN_gen_audio:
- def __init__(self):
-
- self.files= []
- random.seed(version=2)
-
- self.name = random.randbytes(8).hex()
- self.audiocount = 0
- def gen(self,prompt,filename=None):
- self.headers = {
- "Content-Type": "application/json"
- }
- self.json_data = {
- "backend": "auto",
- "model": "tts-1",
- "input": prompt
- }
- try:
- response = requests.post(localai_server_t2s, headers=self.headers, data=json.dumps(self.json_data))
- response.raise_for_status() # Check if the request was successful
- if filename == None :
- filename = folder+self.name+str(self.audiocount)+".wav"
- with open( filename, 'wb') as file:
- file.write(response.content)
- self.files.append(filename)
- self.audiocount += 1
-
- except Exception as err:
- print(f'Other error occurred: {err}') # Print any other error
- return False
- return True
- def get_names(self):
- return self.files
- def flush(self):
- self.files = []
- def delete_all(self):
- for n in self.files:
- os.remove(folder+n)
- concat_N = 4
- def main():
- parser = argparse.ArgumentParser(
- description="Utility for generating content",
- 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 ]
-
- Examples:
- """
- )
- # Adding arguments for --text2speach
- parser.add_argument('--text2speach', action='store_true', help="Text to speech command")
- parser.add_argument('-audio', type=str, help="First argument for text2speach (mandatory if --text2speach is used)")
-
- # Adding arguments for --text2image
- parser.add_argument('--text2image', action='store_true', help="Text to image command")
- parser.add_argument('-size', type=str,nargs=1,help="Size of image WITHxHEIGH")
- parser.add_argument('-image', type=str,nargs=1, help="Third argument for text2image (mandatory if --text2image is used)")
-
- # Adding mutually exclusive arguments
- exclusive_group = parser.add_mutually_exclusive_group()
- exclusive_group.add_argument('-prompt', help='the prompt to send ',type=str,nargs=1)
- exclusive_group.add_argument('-auto-prompt', action='store_true', help='autogenerate prompt')
-
- # Parsing arguments
- args = parser.parse_args()
-
- # Handling arguments
- if args.text2speach:
- if not check_prompt(args) :
- parser.print_help()
- else :
- if args.audio:
- handle_text2speach(args)
- else:
- print("Error: --text2speach requires -audio.")
- parser.print_usage()
- elif args.text2image:
- pattern = r'^\d+(x|X)\d+$'
-
- if not check_prompt(args) :
- parser.print_help()
- else :
- if args.size and args.image :
- match = bool(re.match(pattern, args.size[0]))
- if match :
- handle_text2image(args)
- else:
- print("Error: -size argument sintax wrong ")
- parser.print_usage()
- else:
- print("Error: -image requires -size and -image")
- parser.print_usage()
- else:
- parser.print_help()
- def check_prompt(args):
- if args.prompt or args.auto_prompt :
- if args.prompt and args.auto_prompt :
- print("Error: only one between -prompt and -auto-prompt can be used")
- return False
- return True
- else :
- print("Error: -prompt or -auto-prompt is required")
- return False
-
- def gen_auto_prompt():
- print("auto_prompt could be very slow, if you want to speedup it is possible to use -prompt \"Prompt sentence \" ")
- auto_prompt_list = []
- with open("code/autoprompt.txt","r") as file:
- line_count = 0
- for line in file:
- #print(line)
- # Increment the line count
- line_count += 1
- # Print the current line
- auto_prompt_list.append(line)
- #print(line_count)
- auto_prompt = ""
- for i in range(0,concat_N) :
- auto_prompt += auto_prompt_list[random.randint(0, line_count-1)]
- auto_prompt = auto_prompt.replace('\n', ' ')
- #print(auto_prompt)
- x = XRN_gen_text()
- return x.gen(auto_prompt)
- def handle_text2speach(args):
- if args.auto_prompt:
- prompt = gen_auto_prompt()
- else :
- prompt = args.prompt[0]
- print(prompt)
- x = XRN_gen_audio()
- x.gen(prompt)
- def handle_text2image(args):
- if args.auto_prompt:
- prompt = gen_auto_prompt()
- else :
- prompt = args.prompt[0]
- x = XRN_gen_image()
- x.gen(prompt,args.image[0])
-
- if __name__ == "__main__":
- main()
|