randstrip.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. objects = list()
  73. with open(config["csvLocation"]+"/"+config["csvObj"]) as obj:
  74. csvReader = csv.reader(obj)
  75. for row in csvReader:
  76. if row[0] == indVign:
  77. objects.append( (row[random.randint(3,len(row)-1)],row[1],row[2] ))
  78. return objects
  79. def writeStrip(story,config):
  80. """This function creates the strip returning an image object that could be saved or viewed. It takes an array with filenames as parameter
  81. 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
  82. repeats the last object."""
  83. strip = []
  84. for indVign in story:
  85. try:
  86. vign = Image.open(config["imagesLocation"]+"/"+indVign).convert('RGBA')
  87. addtext = ImageDraw.Draw(vign)
  88. fnt = ImageFont.truetype(config["font"],config["fontSize"])
  89. textVign = fetchText(indVign,config)
  90. if textVign!=0:
  91. try:
  92. for x in range(len(textVign[0])):
  93. text_vign = textVign[1][x]
  94. try:
  95. while text_vign.find('$') != -1:
  96. text_vign = replaceText(text_vign,config)
  97. except AttributeError as err:
  98. print("Problem parsing:")
  99. print(textVign)
  100. print(err)
  101. quit()
  102. text_vign = text_vign.replace('@','\n')
  103. addtext.multiline_text((int(textVign[0][x][0]),int(textVign[0][x][1])),text_vign,fill="#000000",font=fnt,align="center")
  104. except TypeError:
  105. print("Problem finding text for:")
  106. print(indVign)
  107. quit()
  108. obj_list = addThing(indVign,config)
  109. if obj_list!=0:
  110. for obj in obj_list:
  111. if obj[0] == 'R':
  112. objImg = Image.open(config["imagesLocation"]+"/"+prevObj[0])
  113. else:
  114. prevObj = obj
  115. objImg = Image.open(config["imagesLocation"]+"/"+obj[0])
  116. vign.paste(objImg,(int(obj[1]),int(obj[2])))
  117. strip.append(vign)
  118. except FileNotFoundError:
  119. pass
  120. image = Image.new('RGBA',(config["xSize"],config["ySize"]))
  121. xshift=0
  122. for vign in strip:
  123. image.paste(vign,(xshift,0))
  124. xshift += config["panelLength"]
  125. ImageDraw.Draw(image).rectangle([0,0,config["xSize"]-1,config["ySize"]-1], fill=None, outline="black", width=1)
  126. return image
  127. def createStrip(config,specialPlatform=""):
  128. """Create strip and save it
  129. createStrip(str path/filename)"""
  130. try:
  131. story = fetchVign(config)
  132. finalStrip = writeStrip(story,config)
  133. if specialPlatform == "android":
  134. return finalStrip
  135. else:
  136. finalStrip.save(config["saveLocation"]+config["filename"])
  137. return 0
  138. except Exception as err:
  139. return err
  140. def readConfig(profile=False,platform=False):
  141. """Read configuration file"""
  142. try:
  143. with open(fileDir+"/config.json") as f:
  144. config = json.load(f)
  145. except IOError:
  146. print("config.json not found")
  147. return False
  148. if not(profile):
  149. profile = config["defaultProfile"]
  150. else:
  151. profile = profile[0]
  152. try:
  153. checkProfile = config[profile]
  154. except KeyError:
  155. print("Profile "+profile+" not found")
  156. profile = config["defaultProfile"]
  157. saveLocation = checkLocal(config[profile]["saveLocation"])
  158. imagesLocation = checkLocal(config[profile]["imagesLocation"])
  159. csvLocation = checkLocal(config[profile]["csvLocation"])
  160. csvTree = config[profile]["csvTree"]
  161. csvSpeech = config[profile]["csvSpeech"]
  162. csvSubs = config[profile]["csvSubs"]
  163. csvObj = config[profile]["csvObj"]
  164. font = checkLocal(config[profile]["font"])
  165. fontSize = int((config[profile]["fontSize"]))
  166. xSize = config[profile]["xSize"]
  167. ySize = config[profile]["ySize"]
  168. panelLength = config[profile]["panelLength"]
  169. if platform:
  170. token = checkLocal(config[profile][platform]["token"])
  171. filename = checkLocal(config[profile][platform]["filename"])
  172. try:
  173. text = config[profile][platform]["text"]
  174. except KeyError:
  175. text = False
  176. 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}
  177. filename = config[profile]["filename"]
  178. 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}
  179. def checkLocal(directory):
  180. """Checks if it's a relative or absolute path"""
  181. if directory[0] == ".":
  182. return fileDir + directory[1:]
  183. else:
  184. return directory
  185. if __name__ == "__main__":
  186. import argparse
  187. parser = argparse.ArgumentParser()
  188. parser.add_argument('-s','--story',metavar='story',default='',nargs=4,help='story = image file name')
  189. parser.add_argument('-a','--a4',default=False,action='store_true',help='print on an A4 in PDF, needs -o output, disables -x xsize')
  190. parser.add_argument('-m','--multiple',metavar='multiple',default=[1],nargs=1,type=int,help='multiple output (int >0), if no output -o specified, it just tests the stories')
  191. parser.add_argument('-x','--xsize',metavar='xsize',default=0,type=int,nargs=1,help='output image width')
  192. parser.add_argument('-p','--profile',metavar='profile',default="",type=str,nargs=1,help='select a profile registered in config.json, if it doesn\'t exist it will use the default one')
  193. parser.add_argument('-o','--output',metavar='output',const=True,default=False,nargs="?",help='output file, if name not specified, default path will be used')
  194. args = parser.parse_args()
  195. if args.multiple[0] <= 0: #Wrong multiple choice
  196. quit()
  197. config = readConfig(profile=args.profile)
  198. if args.output == True: #Output on but no filename specified
  199. fileName = config["saveLocation"]+config["filename"]
  200. elif type(args.output) == str: #Output specified
  201. fileName = args.output
  202. pdfs = list() #Prepare a list for the PDF
  203. for ist in range(0,args.multiple[0]):
  204. if (args.story == ''): #No story specified
  205. story = fetchVign(config)
  206. else:
  207. story = [] #Story specified
  208. for x in args.story:
  209. story.append(x)
  210. finalStrip = writeStrip(story,config)
  211. if args.a4: #Prints a PDF
  212. finalStrip = finalStrip.resize((2249,516))
  213. pdfs.append(finalStrip)
  214. else:
  215. if args.xsize != 0: #Resize specified
  216. finalStrip = finalStrip.resize((args.xsize[0],int(args.xsize[0]/2400*500)))
  217. if args.multiple[0] == 1: #No multiple selected
  218. if args.output == False:
  219. finalStrip.show()
  220. else:
  221. finalStrip.save(fileName)
  222. else: #Multiple selected
  223. if args.output == False:
  224. print(story)
  225. else:
  226. finalStrip.save(fileName + str(ist).zfill(3) + ".png")
  227. if args.a4:
  228. ypos = 100
  229. nopage = 0
  230. if args.output == False:
  231. print("Output not specified")
  232. quit()
  233. pagePdf = list()
  234. for pag in range(0,int((args.multiple[0]-1)/6+1)):
  235. image = Image.new('RGB',(2479,3508),(255,255,255))
  236. fnt = ImageFont.truetype(config["font"],config["fontSize"])
  237. ImageDraw.Draw(image).text((2479 - 500, 3508 - 200),"https://github.com/oloturia/fumcaso",fill="black",font=fnt)
  238. pagePdf.append(image)
  239. for ist,strip_num in enumerate(range(0,args.multiple[0])):
  240. pagePdf[nopage].paste(pdfs[strip_num],box=(110,ypos))
  241. ypos += 516 + 20
  242. if ypos > 3508-569:
  243. ypos = 100
  244. nopage += 1
  245. if fileName[len(fileName)-4:] != ".pdf":
  246. fileName += ".pdf"
  247. pagePdf[0].save(fileName, resolution=300, save_all=True, append_images=pagePdf[1:])