def removeLowestScore (current_slides, unused_slides_H, unused_slides_V): minimum_score = 1000000; minimum_index = -1; for i in range(len(current_slides)-3): current_score = current_slides[i+1].prev_score + current_slides[i+1].next_score if ( current_score < minimum_score ): minimum_score = current_score minimum_index = i + 1 if (minimum_index > -1): removed_slide = current_slides[minimum_index]; if (removed_slide.h_image is not None): unused_slides_H.append(removed_slide) else: unused_slides_V.append(Slide( v_image_1 = removed_slide.v_image_1, v_tags_1 = removed_slide.v_tags_1, )) unused_slides_V.append(Slide( v_image_1 = removed_slide.v_image_2, v_tags_1 = removed_slide.v_tags_2 ))
def _construct_slide(self, photos): if isinstance(photos, Photo): return Slide([photos]) elif isinstance(photos, list): return Slide(photos) else: raise ArguementUndefinedError
def to_slide_random(photos): # array containing slides slides = [] # go through all horizontal pictures i = 0 print("Sorting horizontal pictures...") while i < len(photos): if photos[i].orientation is 'H': # horizontal pictures are the same as a slide slides.append(Slide(photos[i])) photos.pop(i) # one index back so you end up in the next place i -= 1 i += 1 # find matches for vertical pictures print("Matching vertical pictures to slides...") while len(photos) > 2: print(len(photos), end="\r", flush=True) # look for a random combination of pictures photo = photos[0] other = random.randint(1, len(photos) - 1) if other is not 0: # if 0 not usefull slides.append(Slide(photo, photos[other])) photos.pop(other) photos.pop(0) # print number of unused pictures print(len(photos)) return slides
def doRandomRemove(current_slides, unused_slides_H, unused_slides_V, force): # print("doRandomRemove") if (len(current_slides) < 3): # print("3 or more slides needed for remove.") return remove_index = random.randint(1, len(current_slides)-2) if ( force or removeImprovement(current_slides, remove_index) > 0 ): removed_slide = current_slides[remove_index] if (removed_slide.h_image is not None): unused_slides_H.append(removed_slide) else: unused_slides_V.append(Slide( v_image_1 = removed_slide.v_image_1, v_tags_1 = removed_slide.v_tags_1, )) unused_slides_V.append(Slide( v_image_1 = removed_slide.v_image_2, v_tags_1 = removed_slide.v_tags_2 )) del current_slides[remove_index] return
def merge(vertical_pics): slides = {} # Do not update input struct vertical_pics_copy = copy(vertical_pics) unmatched_pics = {} # for every pic, found a non overlapping pic print('find perfect vertical matching (%s)...' % len(vertical_pics_copy)) keep_going = True while keep_going: if len(vertical_pics_copy) < 2: keep_going = False else: first_pic = vertical_pics_copy.pop( random.choice(list(vertical_pics_copy.keys()))) second_pic = None for i, pic in vertical_pics_copy.items(): if not set(first_pic.tags) & set(pic.tags): second_pic = pic break if second_pic is not None: del vertical_pics_copy[second_pic.id] slides[merge_id(first_pic.id, second_pic.id)] = Slide(first_pic, second_pic) else: unmatched_pics[first_pic.id] = first_pic # for the remaining pics, match it with the less overlapping print('find remaining vertical matching (%s)...' % len(unmatched_pics)) keep_going = True while keep_going: if len(unmatched_pics) < 2: keep_going = False else: first_pic = unmatched_pics.pop( random.choice(list(unmatched_pics.keys()))) second_pic = None tag_count = 0 for i, pic in unmatched_pics.items(): current_tag_count = len(set(first_pic.tags) | set(pic.tags)) if current_tag_count > tag_count: second_pic = pic tag_count = current_tag_count del unmatched_pics[second_pic.id] slides[merge_id(first_pic.id, second_pic.id)] = Slide(first_pic, second_pic) return slides
def arrange(self): # print(f'{filename} reached arrange') shuffle_horizontal, shuffle_vertical = self.horizontal_photos, self.vertical_photos slide_temp = [] for photo_id in shuffle_horizontal: photo = self.photos[photo_id] slide_temp.append(Slide(photos=[photo], tags=photo.tags)) for ix in range(0, len(shuffle_vertical), 2): photos = [self.photos[ix], self.photos[ix + 1]] slide_temp.append( Slide(photos=photos, tags=photos[0].tags | photos[1].tags)) self.slides = slide_temp
def photoCombiner(listOfPic): listpics = [] slide = [] for pic in listOfPic: if (pic.orientation == 'V'): listpics.append(pic) else: slide.append(Slide(pic)) for i in range(0, len(listpics), 2): slide.append(Slide(listpics[i], listpics[i + 1])) return slide
def random_indv(self): indexes = [x for x in range(len(self.photos))] shuffle(indexes) slides = [] unpaired_photo = None for photo_id in indexes: photo = self.photos[photo_id] if photo.is_vertical: if not unpaired_photo: unpaired_photo = photo else: slides.append(Slide(photo, unpaired_photo)) unpaired_photo = None else: slides.append(Slide(photo)) return Individual(slides)
def createSongFile(self, pres_path, song, paths, prefs, ratio): slide = Slide(prefs, ratio) i = 0 # Is this a medley? If so, we will create a Medley page to include all # meta-data for represented hymns. if song['type'] == 'medley': slide.addMedleySlide(song) # Iterate through the PAGE_SEQUENCE to maintain page order for path in paths: if i == 0: if song['type'] == 'medley': medley_meta = song.copy() # This next line works as long as numbers are STRINGS song['number'] = ', '.join(song['number']) slide.addHiddenMetaRecord(slide.slide, medley_meta) slide.addMusicSlide(path, song, 0) else: slide.addMusicSlide(path, song, 1) else: slide.addMusicSlide(path, song, 0) i += 1 slide.addBlackSlide() slide.saveFile(pres_path) log.info("Presenter created", song['type'] + ':', pres_path) return True
def unirVerticales(slides: list, picsV: list): while (picsV): # no esta vacia elto1 = picsV.pop(0) elto2 = maximizarTags( elto1, picsV) # no tengo en cuenta verticales impares... #No existen las verticales impares. Mira que bien slides.append(Slide(elto1, elto2))
def greedy_random_horizontal_make(self, pics): slideshow = [] previous_slide = None index = list(range(len(pics))) random.shuffle(index) for i in index: pic = pics[i] # First, only Horizontal if pic.orientation == 1: continue current_slide = Slide(pic, None) if current_slide.is_valid(): # Horizontal if previous_slide is None: slideshow.append(current_slide) previous_slide = current_slide else: if transition_score(current_slide, previous_slide): # Ok, current slide is valid, add it to slideshow slideshow.append(current_slide) previous_slide = current_slide return slideshow
def to_slide_greedy(photos): # define target nuber of tags per slide number_pics = len(photos) number_tags = 0 for photo in photos: number_tags += len(photo.tags) # array containing slides slides = [] # only vertical should remain slides, photos = get_horizontal(slides, photos) # sort photos by number of tags photos = bucketSort(photos) while len(photos) > 1: photo = photos[len(photos) - 1] photos.pop(len(photos) - 1) max_tags = len(photo.tags) other = len(photos) - 2 for i in range(len(photos) - 100, len(photos) - 1): if i >= 0: num_tags = calc_tags(photo, photos[i]) if num_tags > max_tags: max_tags = num_tags other = i slides.append(Slide(photo, photos[other])) photos.pop(other) return slides
def getSlideShow(photoList): """ :param photoList: a list of Photos :rtype slideShow: a list of Slides """ slideShow = [] verticalPhoto = None for photo in photoList: if photo.isHorizontal: slideShow.append(Slide(photo)) else: if verticalPhoto: slideShow.append(Slide(verticalPhoto, secondPhoto=photo)) verticalPhoto = None else: verticalPhoto = photo return slideShow
def init(): with open('config.json', 'r') as f: jdata = json.load(f) slideData = jdata['slides'] for slide in slideData: print(slide['file']) temp = Slide(slide) slides.append(temp)
def greedy_random_vertical_make(self, pics): slideshow = [] previous_slide = None current_slide = None pics_copy = copy.copy(pics) keep_going = True # print('Starting greedy slideshow maker...') while keep_going: current_slideshow = [] index = list(pics_copy.keys()) random.shuffle(index) for i in index: pic = pics_copy[i] # First, only Vertical if pic.orientation == 0: continue if current_slide is None: current_slide = Slide(pic, None) continue else: current_slide.add(pic) if current_slide.is_valid(): if previous_slide is None: slideshow.append(current_slide) current_slideshow.append(current_slide) previous_slide = current_slide else: if transition_score(current_slide, previous_slide): # Ok, current slide is valid, add it to slideshow slideshow.append(current_slide) current_slideshow.append(current_slide) previous_slide = current_slide current_slide = None if not current_slideshow: # Stop when no more slideshow found keep_going = False else: # print('Adding %s slides' % len(current_slideshow)) for slide in current_slideshow: del pics_copy[slide.pic_a.id] del pics_copy[slide.pic_b.id] return slideshow
def arrange2(self): d = self.tag_to_id_map # print(d) sorted_keys = sorted(d, key=lambda k: len(d[k]), reverse=True) # print(sorted_keys) hz, vt = set(), set() used = set() slide_temp = [] vt_temp = [] for key in sorted_keys: # print(key, d[key]) for id in d[key]: if id not in used: used.add(id) # print(used) if self.photos[id].orient == 'H': slide_temp.append( Slide(photos=[self.photos[id]], tags=self.photos[id].tags)) assert id not in hz hz.add(id) else: if len(vt) < 2: vt_temp.append(id) if len(vt) == 2: photos = [ self.photos[vt_temp[0]], self.photos[vt_temp[1]] ] slide_temp.append( Slide(photos=photos, tags=photos[0].tags | photos[1].tags)) assert id not in vt vt.add(id) assert len(used) == len(self.vertical_photos) + len( self.horizontal_photos) assert len(vt) == len(self.vertical_photos) assert len(hz) == len(self.horizontal_photos) # print(hz, vt) self.horizontal_photos = list(hz) self.vertical_photos = list(vt) self.slides = slide_temp
def estoTeSacaUnaListaDeSlides(slides): picsVerticales = [] for line in fileinput.input(): if not fileinput.isfirstline(): #a tomar viento la primera linea separada = line[:len(line) - 1].split(' ') # Separamos por ' ' fila = fileinput.lineno() # n de fila picLeido = Pic(fila - 2, separada) # construyo el leido... if (picLeido.orientation()): picsVerticales.append(picLeido) else: slides.append(Slide(picLeido)) # y lo anado a la lista unirVerticales(slides, picsVerticales)
def loadSlides(pageName): # https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python sList = [] tempList = readFile('static\\' + pageName + '.csv') for i in tempList: imgPath = '../static/images/' + pageName + '/' + i[0] textPath = 'static\\text\\' + i[2] txt = '' if i[2] != "": txt = listToPlain(readFile(textPath)) sList.append(Slide(imgPath, i[1], txt, i[3])) return sList
def read_input(filename): lines = open(filename).readlines() P = int(lines[0]) tags = [] v = [] h = [] for i, row in enumerate(lines[1:]): elements = row.strip().split(' ') O = elements[0] T = elements[2:] if O == 'H': h.append(Slide(h_tags=T, h_image=i)) else: v.append(Slide(v_tags_1=T, v_image_1=i)) return P, v, h
def get_horizontal(slides, photos): i = 0 print("Sorting horizontal pictures...") while i < len(photos): if photos[i].orientation is 'H': # horizontal pictures are the same as a slide slides.append(Slide(photos[i])) photos.pop(i) # one index back so you end up in the next place i -= 1 i += 1 return slides, photos
def to_slide(photos): # array containing slides slides = [] # go through all horizontal pictures i = 0 print("Sorting horizontal pictures...") while i < len(photos): if photos[i].orientation is 'H': # horizontal pictures are the same as a slide slides.append(Slide(photos[i])) photos.pop(i) # one index back so you end up in the next place i -= 1 i += 1 # find matches for vertical pictures print("Matching vertical pictures to slides...") while len(photos) > 1: print(len(photos), end="\r", flush=True) # look for an "ok" combination of pictures photo = photos[0] max_tags = len(photo.tags) other = 0 for i in range(1, len(photos)): num_tags = calc_tags(photo, photos[i]) if num_tags > max_tags: max_tags = num_tags other = i if other is not 0: # if 0 not useful slides.append(Slide(photo, photos[other])) photos.pop(other) photos.pop(0) # print number of unused pictures print(len(photos)) return slides
def make_scene(): """Returns the scene as an ElementTree.Element""" scene = ET.Element('scene') el = ET.SubElement(scene, 'description') el.set( 'text', 'Some ' + random.choice( ('weird', 'crazy')) + ' scene generated by make_scene.py') el = ET.SubElement(scene, 'duration') el.set('time', '60.0') el = ET.SubElement(scene, 'integrator') el.set('type', 'forward-backward-euler') el.set('dt', '0.01') #el = ET.SubElement(scene, 'maxsimfreq') #el.set('max', '500.0') el = ET.SubElement(scene, 'collision') #el.set('type', 'simple') #el.set('COR', '1') el.set('type', 'penalty') el.set('k', '10000') el.set('thickness', '0') el = ET.SubElement(scene, 'scenetag') el.set('tag', 'ParticleFountain') scene.append(ET.Element('simplegravity', {'fx': '0.0', 'fy': '-0.1'})) scene.append( ET.Element('backgroundcolor', { 'r': '0.7', 'g': '0.5', 'b': '1' })) # scene.append(make_particle()) # scene.append(make_particle(px='0.0', m='500', radius='0.1', vx='4')) # sine = make_sine() # for s in sine: # scene.append(s) pf = ParticleFactory() slide = Slide(pos=0, factory=pf) for s in slide.make(): scene.append(s) return scene
def estoTeSacaUnaListaDeSlides(slides): picsVerticales = [] for line in fileinput.input(): if not fileinput.isfirstline(): #a tomar viento la primera linea separada = line[:len(line) - 1].split(' ') # Separamos por ' ' fila = fileinput.lineno() # n de fila picLeido = Pic(fila - 2, separada) # construyo el leido... if (picLeido.orientation() ): # es vertical, pa la lista de verticales picsVerticales.append(picLeido) else: # no lo es, a los slides directo slides.append(Slide(picLeido)) # unimos lo verticales a los slides, maximizando tags unirVerticales(slides, picsVerticales)
def slide_from_json(self, data): filepath = data[u'photo_placeholder_url'] image = wx.Image(filepath, wx.BITMAP_TYPE_ANY) s = Slide(data[u'id'], image, self.name) s.title = data[u'title'] s.image = image s.text = data[u'body'] s.start = data[u'start'] s.finish = data[u'finish'] s.shareable = data[u'shareable'] s.choices = [(choice[u'body'], choice[u'to_node']) for choice in data[u'links']] return s
def mutate_vertical(self): i = randint(0, len(self.vertical) - 1) j = -1 while j != i: j = randint(0, len(self.vertical) - 1) if i > 0: self.total_score -= self.score(i - 1) if i < len(self.slides) - 1: self.total_score -= self.score(i) if j > 0 and j != i + 1: self.total_score -= self.score(j - 1) if j < len(self.slides) - 1 and j != i - 1: self.total_score -= self.score(j) # i,j are only vertical photo1, photo2 = list(self.slides[i].photos) photo3, photo4 = list(self.slides[j].photos) self.slides[i] = Slide(photo1, photo3) self.slides[j] = Slide(photo2, photo4) if i > 0: self.total_score += self.score(i - 1) if i < len(self.slides) - 1: self.total_score += self.score(i) if j > 0 and j != i + 1: self.total_score += self.score(j - 1) if j < len(self.slides) - 1 and j != i - 1: self.total_score += self.score(j)
def greedy_vertical_make(self, pics): slideshow = [] previous_slide = None current_slide = None pics_copy = copy.copy(pics) keep_going = True while keep_going: current_slideshow = [] for i, pic in pics_copy.items(): # First, only Vertical if pic.orientation == 0: continue if current_slide is None: current_slide = Slide(pic, None) continue else: current_slide.add(pic) if current_slide.is_valid(): if previous_slide is None: slideshow.append(current_slide) current_slideshow.append(current_slide) previous_slide = current_slide else: if transition_score(current_slide, previous_slide): # Ok, current slide is valid, add it to slideshow slideshow.append(current_slide) current_slideshow.append(current_slide) previous_slide = current_slide current_slide = None if not current_slideshow: # Stop when no more slideshow found keep_going = False else: # print('Adding %s slides' % len(current_slideshow)) for slide in current_slideshow: del pics_copy[slide.pic_a.id] del pics_copy[slide.pic_b.id] return slideshow
def dump_slide(slide_path, args): tmp_path = transfer_to_ramdisk(slide_path) print(tmp_path) basename = os.path.basename(slide_path) try: svs = Slide(slide_path=tmp_path, preprocess_fn=lambda x: x, normalize_fn=lambda x: x, process_mag=5, process_size=128, oversample_factor=1.) print(len(svs.tile_list)) # Save the foreground image for reference fg = svs.foreground fg_fn = os.path.join(args.out_dir, basename.replace('.svs', '_fg.jpg')) cv2.imwrite(fg_fn, fg * 255) # Dump tiles sequentially height = _int64_feature(args.size) width = _int64_feature(args.size) record_path = os.path.join(args.out_dir, basename.replace('.svs', '.tfrecord')) writer = tf.python_io.TFRecordWriter(record_path) for img, ix in svs.generator(): img_raw = img.tostring() example = tf.train.Example(features=tf.train.Features( feature={ 'height': height, 'width': width, 'img': _bytes_feature(img_raw) })) writer.write(example.SerializeToString()) if ix % 500 == 0: print('Writing [{} / {}]'.format(ix, len(svs.tile_list))) writer.close() except Exception as e: print(e) finally: os.remove(tmp_path) print('Done. {} cleaned.'.format(tmp_path))
def build_graph(pics, pics_per_tag): graph = Graph() # Add node to graph for uid, pic in pics.items(): node = Node(uid, Slide(pic)) graph.add_node(node) # Link nodes in graph for tag, tag_pics in pics_per_tag.items(): for pic_id_1 in tag_pics: pic_1 = pics[pic_id_1] for pic_id_2 in tag_pics: pic_2 = pics[pic_id_2] if pic_id_1 != pic_id_2: graph.add_link(pic_1.id, pic_2.id) return graph
def createScriptureFile(self, path, font_sz, ref, text, meta, ratio): slide = Slide(meta, ratio) # Multiple-paged scriptures are delimited by "¶" pg_num = 0 pages = text.split('¶') for page in pages: # There are \n chars at beginning of pages. # Strip it, except first page. if pg_num: page = page.lstrip("\n") slide.addTextSlide(slide, page, font_sz) #if pg_num == 0 and len(pages) > 1: # slide.addHiddenMetaRecord(slide, meta) pg_num += 1 slide.addScriptureTextReference(slide, ref) #if len(pages) == 1: # slide.addHiddenMetaRecord(slide, meta) slide.addBlackSlide() slide.saveFile(path) log.info("Presenter created scripture:", path)
def mutate_random(self): i = randint(0, len(self.slides) - 3) j = randint(i + 2, len(self.slides) - 1) self.total_score -= self.score(i) self.total_score -= self.score(j - 1) if j < len(self.slides) - 1: self.total_score -= self.score(j) s = Slide(self.slides[j].photos[0], self.slides[j].photos[1]) for k in range(j - 1, i, -1): self.slides[k + 1] = self.slides[k] self.slides[i + 1] = s self.total_score += self.score(i) self.total_score += self.score(i + 1) if j < len(self.slides) - 1: self.total_score += self.score(j) self.vertical = [i for i, x in enumerate(self.slides) if x.is_vertical]