randstrip.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. #!/usr/bin/python3
  2. from PIL import Image
  3. from PIL import ImageFont
  4. from PIL import ImageDraw
  5. import csv
  6. import random
  7. import os
  8. import json
  9. fileDir = os.path.dirname(os.path.abspath(__file__))
  10. def replaceText(text,config):
  11. """This function replace $WILDCARD with a word found in subs.csv
  12. subs.csv definition is 1st colum $WILDCARD, subsequent columns, possible values (chosen at random), delimiter is ;"""
  13. with open(config["csvLocation"]+"/"+config["csvSubs"]) as subs:
  14. csvReader = csv.reader(subs,delimiter=";")
  15. for row in csvReader:
  16. if text.find(row[0]) != -1:
  17. text = text.replace(row[0],row[random.randint(1,len(row)-1)],1)
  18. return text
  19. print("Parsing error \""+text+"\" not found")
  20. quit()
  21. def fetchText(indText,config):
  22. """This function fetch the text for the image with two characters
  23. rtext.csv definition is: 1st column the name of the file (i.e. B001.png), 2nd number of actors (at the moment
  24. they are limited to two; then a couple of columns or each actor with x and y coord of the strings; after the coords the outcomes,
  25. one column for each actor
  26. Delimiter is ; and line feeds @, if there aren't any options, it returns 0 (no text)
  27. It returns two arrays, coords is a tuple (x,y) and result is the outcome"""
  28. with open(config["csvLocation"]+"/"+config["csvSpeech"]) as rtext:
  29. csvReader = csv.reader(rtext,delimiter=';')
  30. for row in csvReader:
  31. if row[0]==indText:
  32. noActors = int(row[1])
  33. if noActors == 0:
  34. return 0
  35. else:
  36. firstElement = 2+(noActors*2)
  37. lastElement = len(row)-(noActors-1)
  38. randQuote = random.randrange(firstElement,lastElement,noActors)
  39. coords = []
  40. result = []
  41. for x in range(0,noActors):
  42. coords.append((row[2+x*2],row[3+x*2]))
  43. result.append(row[randQuote+x])
  44. return coords,result
  45. def fetchVign(config):
  46. """This functions fetch an image, randomly, chosen from a markov tree defined in ram.csv
  47. ram.csv definition is: 1st column the name of the image (without extension), subsequent columns, possible outcomes chosen randomly
  48. It returns an array with the file names"""
  49. starts = []
  50. startdest = []
  51. nvign = 0
  52. currVign = "000"
  53. story = []
  54. with open(config["csvLocation"]+"/"+config["csvTree"]) as ram:
  55. csvReader = csv.reader(ram)
  56. for row in csvReader:
  57. starts.append(row[0])
  58. startdest.append(row)
  59. while nvign <100:
  60. story.append(startdest[starts.index(currVign)][random.randint(1,len(startdest[starts.index(currVign)])-1)])
  61. currVign = story[nvign]
  62. if currVign == "END":
  63. return story
  64. story[nvign]+=".png"
  65. nvign +=1
  66. print("tree with no END")
  67. quit()
  68. def addThing(indVign,config):
  69. """This function adds a small image (object) to a larger image
  70. obj.csv definition is: name of the image (i.e. A001.png), x-coord, y-coord, subsequent columns possible outcomes
  71. It returns a tuple (object file name, x, y)"""
  72. with open(config["csvLocation"]+"/"+config["csvObj"]) as obj:
  73. csvReader = csv.reader(obj)
  74. for row in csvReader:
  75. if row[0] == indVign:
  76. return row[random.randint(3,len(row)-1)],row[1],row[2]
  77. return 0
  78. def writeStrip(story,config):
  79. """This function creates the strip returning an image object that could be saved or viewed. It takes an array with filenames as parameter
  80. The first image is always 000, then appends to strip the files, then decorates it fetching text and adding objects. If the object is an R, then
  81. repeats the last object."""
  82. strip = []
  83. for indVign in story:
  84. try:
  85. vign = Image.open(config["imagesLocation"]+"/"+indVign).convert('RGBA')
  86. addtext = ImageDraw.Draw(vign)
  87. fnt = ImageFont.truetype(config["font"],config["fontSize"])
  88. textVign = fetchText(indVign,config)
  89. if textVign!=0:
  90. try:
  91. for x in range(len(textVign[0])):
  92. text_vign = textVign[1][x]
  93. try:
  94. while text_vign.find('$') != -1:
  95. text_vign = replaceText(text_vign,config)
  96. except AttributeError as err:
  97. print("Problem parsing:")
  98. print(textVign)
  99. print(err)
  100. quit()
  101. text_vign = text_vign.replace('@','\n')
  102. addtext.multiline_text((int(textVign[0][x][0]),int(textVign[0][x][1])),text_vign,fill="#000000",font=fnt,align="center")
  103. except TypeError:
  104. print("Problem finding text for:")
  105. print(indVign)
  106. quit()
  107. obj = addThing(indVign,config)
  108. if obj!=0:
  109. if obj[0] == 'R':
  110. objImg = Image.open(config["imagesLocation"]+"/"+prevObj[0])
  111. else:
  112. prevObj = obj
  113. objImg = Image.open(config["imagesLocation"]+"/"+obj[0])
  114. vign.paste(objImg,(int(obj[1]),int(obj[2])))
  115. strip.append(vign)
  116. except FileNotFoundError:
  117. pass
  118. image = Image.new('RGBA',(config["xSize"],config["ySize"]))
  119. xshift=0
  120. for vign in strip:
  121. image.paste(vign,(xshift,0))
  122. xshift += config["panelLength"]
  123. return image
  124. def createStrip(config,specialPlatform=""):
  125. """Create strip and save it
  126. createStrip(str path/filename)"""
  127. try:
  128. story = fetchVign(config)
  129. finalStrip = writeStrip(story,config)
  130. if specialPlatform == "android":
  131. return finalStrip
  132. else:
  133. finalStrip.save(config["saveLocation"]+config["filename"])
  134. return 0
  135. except Exception as err:
  136. return err
  137. def readConfig(profile=False,platform=False):
  138. """Read configuration file"""
  139. try:
  140. with open(fileDir+"/config.json") as f:
  141. config = json.load(f)
  142. except IOError:
  143. print("config.json not found")
  144. return False
  145. if not(profile):
  146. profile = config["defaultProfile"]
  147. else:
  148. profile = profile[0]
  149. try:
  150. checkProfile = config[profile]
  151. except KeyError:
  152. print("Profile "+profile+" not found")
  153. quit()
  154. saveLocation = checkLocal(config[profile]["saveLocation"])
  155. imagesLocation = checkLocal(config[profile]["imagesLocation"])
  156. csvLocation = checkLocal(config[profile]["csvLocation"])
  157. csvTree = config[profile]["csvTree"]
  158. csvSpeech = config[profile]["csvSpeech"]
  159. csvSubs = config[profile]["csvSubs"]
  160. csvObj = config[profile]["csvObj"]
  161. font = checkLocal(config[profile]["font"])
  162. fontSize = int((config[profile]["fontSize"]))
  163. xSize = config[profile]["xSize"]
  164. ySize = config[profile]["ySize"]
  165. panelLength = config[profile]["panelLength"]
  166. if platform:
  167. token = checkLocal(config[profile][platform]["token"])
  168. filename = checkLocal(config[profile][platform]["filename"])
  169. try:
  170. text = config[profile][platform]["text"]
  171. except KeyError:
  172. text = False
  173. return {"saveLocation":saveLocation,"imagesLocation":imagesLocation,"csvLocation":csvLocation,"fontSize":fontSize,"font":font,"token":token,"filename":filename,"xSize":xSize,"ySize":ySize,"panelLength":panelLength,"csvTree":csvTree,"csvSpeech":csvSpeech,"csvSubs":csvSubs,"csvObj":csvObj,"text":text}
  174. filename = config[profile]["filename"]
  175. return {"saveLocation":saveLocation,"imagesLocation":imagesLocation,"csvLocation":csvLocation,"fontSize":fontSize,"font":font,"filename":filename,"xSize":xSize,"ySize":ySize,"panelLength":panelLength,"csvTree":csvTree,"csvSpeech":csvSpeech,"csvSubs":csvSubs,"csvObj":csvObj}
  176. def checkLocal(directory):
  177. """Checks if it's a relative or absolute path"""
  178. if directory[0] == ".":
  179. return fileDir + directory[1:]
  180. else:
  181. return directory
  182. if __name__ == "__main__":
  183. import argparse
  184. parser = argparse.ArgumentParser()
  185. parser.add_argument('-s','--story',metavar='story',default='',nargs=4,help='name of the images')
  186. parser.add_argument('-m','--multiple',metavar='multiple',default=[1],nargs=1,type=int,help='multiple output (int >0)')
  187. parser.add_argument('-x','--xsize',metavar='xsize',default=0,type=int,nargs=1,help='resize image x')
  188. parser.add_argument('-p','--profile',metavar='profile',default="",type=str,nargs=1,help='profile')
  189. parser.add_argument('-o','--output',metavar='output',const=True,default=False,nargs="?",help='output file, if name not specified, default path will be used')
  190. args = parser.parse_args()
  191. if args.multiple[0] <= 0: #Wrong multiple choice
  192. quit()
  193. config = readConfig(profile=args.profile)
  194. if args.output == True: #Output on but no filename specified
  195. fileName = config["saveLocation"]+config["filename"]
  196. elif type(args.output) == str: #Output specified
  197. fileName = args.output
  198. for ist in range(0,args.multiple[0]):
  199. if (args.story == ''): #No story specified
  200. story = fetchVign(config)
  201. else:
  202. story = [] #Story specified
  203. for x in args.story:
  204. story.append(x)
  205. finalStrip = writeStrip(story,config)
  206. if args.xsize != 0: #Resize specified
  207. finalStrip = finalStrip.resize((args.xsize[0],int(args.xsize[0]/2400*500)))
  208. if args.multiple[0] == 1: #No multiple selected
  209. if args.output == False:
  210. finalStrip.show()
  211. else:
  212. finalStrip.save(fileName)
  213. else: #Multiple selected
  214. if args.output == False:
  215. print(story)
  216. else:
  217. finalStrip.save(str(ist)+fileName+".png")