Spaces:
Runtime error
Runtime error
Commit Β·
ce8f63e
1
Parent(s): 1ce5a2b
dynamic layout
Browse files61 unmodified lines6263646566676883 unmodified lines152153154155156157158197 unmodified lines3563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953966 unmodified lines40340440540640740840941041141241341441541641741841942042142242342442542642728 unmodified lines45645745845946046146216 unmodified lines47948048148248348448562 unmodified lines54854955055155255355455555611 unmodified lines5685695705715725735745755765775785795805815825835 unmodified lines58959059159259359459559659759859960060160260360460560660760860999 unmodified lines7097107117127137147151 unmodified line71771871972072172272313 unmodified lines737738739740741742743136 unmodified lines88088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994010 unmodified lines95195295395495595695795895996096110 unmodified lines97297397497597697720 unmodified lines998999100010011002100310041005100610071008100910105 unmodified lines10161017101810191020102118 unmodified lines104010411042104310441045104661 unmodified linesEOS_STRINGS = ["<end_of_utterance>", "\nUser:"]STOP_SUSPECT_LIST = []GRADIO_LINK = "https://huggingfacem4-ai-meme-generator.hf.space"API_TOKEN = os.getenv("HF_AUTH_TOKEN")IDEFICS_LOGO = "https://huggingface.co/spaces/HuggingFaceM4/idefics_playground/resolve/main/IDEFICS_logo.png"83 unmodified linestmp_filename = H.preprocess(H.value)DEFAULT_IMAGES_TMP_PATH_TO_URL[tmp_filename] = f"https://huggingface.co/spaces/HuggingFaceM4/AI_Meme_Generator/resolve/main/example_images/{image_dir}/{im_path}"# Utils to handle the image markdown display logic197 unmodified linesreturn resized_imgdef make_new_lines(draw, image, font, text_is_too_long, lines, num_lines, num_loops):max_len_increment = 0while text_is_too_long and max_len_increment < 10:new_lines = lines.copy()last_line_with_backslash = insert_backslash(new_lines[-1],max_length=(len(new_lines[-1]) + max_len_increment)// (num_lines - num_loops),)penultimate_line, last_line = (last_line_with_backslash.split("\n")[0],last_line_with_backslash.split("\n")[1],)new_lines.pop(-1)new_lines.append(penultimate_line)new_lines.append(last_line)# If the we haven't reached the last line, we split it againif len(new_lines) < num_lines:new_lines, text_width, text_is_too_long = make_new_lines(draw=draw,image=image,font=font,text_is_too_long=text_is_too_long,lines=new_lines,num_lines=num_lines,num_loops=num_loops + 1,)text_width = max([draw.textlength(line, font) for line in new_lines])text_is_too_long = text_width > image.widthmax_len_increment += 1if not text_is_too_long:lines = new_linesreturn lines, text_width, text_is_too_longdef test_font_size(draw,image,6 unmodified lines):text_width = draw.textlength(text, font)text_is_too_long = Truelines = [text]while font.size > min_font and text_is_too_long:font = ImageFont.truetype(f"fonts/{font_meme_text}.ttf", size=font.size - font_size_reduction)if num_lines == 1:text_width = draw.textlength(text, font)text_is_too_long = text_width > image.widthelse:lines, text_width, text_is_too_long = make_new_lines(draw=draw,image=image,font=font,text_is_too_long=text_is_too_long,lines=lines,num_lines=num_lines,num_loops=0,)temp_text = "\n".join(lines)if not text_is_too_long and num_lines > 1:text = temp_text28 unmodified linesinitial_font_size = 80text_is_too_long = Truenum_lines = 0while text_is_too_long and num_lines < 8:num_lines += 1font = ImageFont.truetype(f"fonts/{font_meme_text}.ttf", size=initial_font_size)text, font, text_width, text_is_too_long = test_font_size(16 unmodified linesoutline_width = 2text_x = (image_width - text_width) / 2text_y = image_height - num_lines * font.size - 10 - 2 * num_linesif text_at_the_top:text_y = 062 unmodified linesreturn resulting_list, current_user_prompt_list# dope_callback = gr.CSVLogger()# problematic_callback = gr.CSVLogger()textbox = gr.Textbox(placeholder="Upload an image and ask the AI to create a meme!",11 unmodified linesvisible=False,avatar_images=[None, BOT_AVATAR],)css = """.gradio-container{max-width: 970px!important}h1{display: flex;align-items: center;justify-content: center;gap: .25em}"""with gr.Blocks(title="AI Meme Generator", theme=gr.themes.Base(), css=css) as demo:with gr.Row(scale=0.5):gr.HTML("""<h1 align="center">AI Meme Generator <span style="font-size: 13px;">powered by <a href="https://huggingface.co/blog/idefics">IDEFICS</a></span><img width=40 height=40 src="https://cdn-uploads.huggingface.co/production/uploads/624bebf604abc7ebb01789af/v770xGti5vH1SYLBgyOO_.png" /></h1>""")with gr.Row(elem_id="model_selector_row"):model_selector = gr.Dropdown(choices=MODELS,5 unmodified linesvisible=False,)with gr.Row(equal_height=True):with gr.Column(equal_height=1):imagebox = gr.Image(type="filepath", label="Image to meme", height=400, visible=True)with gr.Group():with gr.Row():textbox.render()with gr.Row():submit_btn = gr.Button(value="βΆοΈ Submit", visible=True)clear_btn = gr.ClearButton([textbox, imagebox, chatbot], value="π§Ή Clear")regenerate_btn = gr.Button(value="π Regenerate", visible=True)upload_btn = gr.UploadButton("π Upload image", file_types=["image"], visible=False)with gr.Accordion("Advanced settings", open=False, visible=True99 unmodified linesinputs=decoding_strategy,outputs=top_p,)with gr.Column(scale=2):generated_memes_gallery = gr.Gallery(# value="Images generated will appear here",label="IDEFICS Generated Memes",1 unmodified lineelem_id="generated_memes_gallery",show_download_button=True,show_share_button=True,).style(columns=[2], object_fit="contain", height=600)with gr.Row(equal_height=True):with gr.Box(elem_id="gallery_box"):gallery_type_choice = gr.Radio(13 unmodified lines# value= value given by gallery_type_choice,label="Templates Gallery",allow_preview=False,columns=[6],elem_id="gallery",show_share_button=False,height=400,136 unmodified lines# yield "", None, chat_historyfull_text += acc_textacc_text = ""textbox.submit(fn=lambda: "", inputs=[], outputs=[generated_memes_gallery], queue=False).then(fn=model_inference,inputs=[model_selector,system_prompt,textbox,chatbot,imagebox,decoding_strategy,temperature,max_new_tokens,repetition_penalty,top_p,all_caps_meme_text,text_at_the_top,font_meme_text,],outputs=[textbox, generated_memes_gallery, chatbot],)imagebox.upload(fn=lambda: "", inputs=[], outputs=[generated_memes_gallery], queue=False).then(fn=lambda: "Write a meme about this image.",inputs=[],outputs=[textbox],queue=False,).then(fn=model_inference,inputs=[model_selector,system_prompt,textbox,chatbot,imagebox,decoding_strategy,temperature,max_new_tokens,repetition_penalty,top_p,all_caps_meme_text,text_at_the_top,font_meme_text,],outputs=[textbox,generated_memes_gallery,chatbot,],)submit_btn.click(fn=lambda: "", inputs=[], outputs=[generated_memes_gallery], queue=False).then(fn=model_inference,inputs=[model_selector,10 unmodified linestext_at_the_top,font_meme_text,],outputs=[textbox,generated_memes_gallery,chatbot,],)def remove_last_turn(chat_history):10 unmodified linesfn=remove_last_turn,inputs=chatbot,outputs=[chatbot, textbox, generated_memes_gallery],).then(fn=model_inference,inputs=[20 unmodified linesupload_btn.upload(add_file, [upload_btn], [imagebox, upload_btn], queue=False)submit_btn.click(lambda: gr.update(label="π Upload image", interactive=True), [], upload_btn)textbox.submit(lambda: gr.update(label="π Upload image", interactive=True), [], upload_btn)clear_btn.click(lambda: gr.update(label="π Upload image", interactive=True), [], upload_btn)gallery_type_choice.change(fn=choose_gallery,5 unmodified linesfn=add_file_gallery,inputs=[template_gallery],outputs=[textbox, imagebox, generated_memes_gallery],).success(fn=model_inference,inputs=[18 unmodified lines],)demo.load(fn=choose_gallery, inputs=[gallery_type_choice], outputs=[template_gallery])demo.queue(concurrency_count=40, max_size=40)demo.launch()61 unmodified lines6263646566676883 unmodified lines152153154155156157158197 unmodified lines3563573583593603616 unmodified lines36836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144228 unmodified lines47147247347447547647716 unmodified lines49449549649749849950062 unmodified lines56356456556656756856957011 unmodified lines5825835845855865875885895905915925935945955965975985 unmodified lines60460560660760860961061161261361461561661761861962062162262362462599 unmodified lines7257267277287297307311 unmodified line73373473573673773873974074113 unmodified lines755756757758759760761136 unmodified lines89889990090190290390490590690790890991091191291391410 unmodified lines92592692792892993093110 unmodified lines94294394494594694794820 unmodified lines9699709719729739749759769779789799809815 unmodified lines98798898999099199299399499599618 unmodified lines101510161017101810191020102161 unmodified linesEOS_STRINGS = ["<end_of_utterance>", "\nUser:"]STOP_SUSPECT_LIST = []GRADIO_LINK = "https://multimodalart-ai-meme-generator.hf.space"API_TOKEN = os.getenv("HF_AUTH_TOKEN")IDEFICS_LOGO = "https://huggingface.co/spaces/HuggingFaceM4/idefics_playground/resolve/main/IDEFICS_logo.png"83 unmodified linestmp_filename = H.preprocess(H.value)DEFAULT_IMAGES_TMP_PATH_TO_URL[tmp_filename] = f"https://huggingface.co/spaces/multimodalart/AI_Meme_Generator/resolve/main/example_images/{image_dir}/{im_path}"# Utils to handle the image markdown display logic197 unmodified linesreturn resized_imgdef test_font_size(draw,image,6 unmodified lines):text_width = draw.textlength(text, font)text_is_too_long = Trueif num_lines == 1:while font.size > min_font and text_is_too_long:font = ImageFont.truetype(f"fonts/{font_meme_text}.ttf", size=font.size - font_size_reduction)text_width = draw.textlength(text, font)text_is_too_long = text_width > image.widthelif num_lines == 2:while font.size > min_font and text_is_too_long:font = ImageFont.truetype(f"fonts/{font_meme_text}.ttf", size=font.size - font_size_reduction)max_len_increment = 0while (text_is_too_longand max_len_increment < 10and max_len_increment < (len(text)) // 2):temp_text = insert_backslash(text, max_length=(len(text) + max_len_increment) // 2)first_line, second_line = (temp_text.split("\n")[0],temp_text.split("\n")[1],)text_width = max(draw.textlength(first_line, font),draw.textlength(second_line, font),)text_is_too_long = text_width > image.widthmax_len_increment += 1elif num_lines == 3:while font.size > min_font and text_is_too_long:font = ImageFont.truetype(f"fonts/{font_meme_text}.ttf", size=font.size - font_size_reduction)max_len_incr_1_split = 0while text_is_too_long and max_len_incr_1_split < 10:first_temp_text = insert_backslash(text, max_length=(len(text) + max_len_incr_1_split) // 3)first_line, second_line = (first_temp_text.split("\n")[0],first_temp_text.split("\n")[1],)max_len_incr_2_split = 0while text_is_too_long and max_len_incr_2_split < 10:temp_text_second_line = insert_backslash(second_line,max_length=(len(second_line) + max_len_incr_2_split) // 2,)second_line_1, second_line_2 = (temp_text_second_line.split("\n")[0],temp_text_second_line.split("\n")[1],)temp_text = first_line + "\n" + second_line_1 + "\n" + second_line_2text_width = max(draw.textlength(first_line, font),draw.textlength(second_line_1, font),draw.textlength(second_line_2, font),)text_is_too_long = text_width > image.widthmax_len_incr_2_split += 1max_len_incr_1_split += 1else:raise (ValueError("num_lines can only be 1, 2 or 3"))if not text_is_too_long and num_lines > 1:text = temp_text28 unmodified linesinitial_font_size = 80text_is_too_long = Truenum_lines = 0while text_is_too_long and num_lines < 3:num_lines += 1font = ImageFont.truetype(f"fonts/{font_meme_text}.ttf", size=initial_font_size)text, font, text_width, text_is_too_long = test_font_size(16 unmodified linesoutline_width = 2text_x = (image_width - text_width) / 2text_y = image_height - num_lines * font.size - 10 - num_linesif text_at_the_top:text_y = 062 unmodified linesreturn resulting_list, current_user_prompt_listdef expand_layout():return gr.Column(scale=2), gr.Gallery(height=682)textbox = gr.Textbox(placeholder="Upload an image and ask the AI to create a meme!",11 unmodified linesvisible=False,avatar_images=[None, BOT_AVATAR],)css='''.gradio-container{max-width: 1000px!important}h1{display: flex;align-items: center;justify-content: center;gap: .25em}*{transition: width 0.5s ease, flex-grow 0.5s ease}'''with gr.Blocks(title="AI Meme Generator", theme=gr.themes.Base(), css=css) as demo:with gr.Row(scale=0.5):gr.HTML("""<h1 align="center">AI Meme Generator <span style="font-size: 13px;">powered by <a href="https://huggingface.co/blog/idefics">IDEFICS</a></span><img width=40 height=40 src="https://cdn-uploads.huggingface.co/production/uploads/624bebf604abc7ebb01789af/v770xGti5vH1SYLBgyOO_.png" /></h1>""")with gr.Row(elem_id="model_selector_row"):model_selector = gr.Dropdown(choices=MODELS,5 unmodified linesvisible=False,)with gr.Row(equal_height=True):#scale=2 when expandedwith gr.Column(scale=4, min_width=250) as upload_area:imagebox = gr.Image(type="filepath", label="Image to meme", height=272, visible=True)with gr.Group():with gr.Row():textbox.render()with gr.Row():submit_btn = gr.Button(value="βΆοΈ Submit", visible=True, min_width=120)clear_btn = gr.ClearButton([textbox, imagebox, chatbot], value="π§Ή Clear", min_width=120)regenerate_btn = gr.Button(value="π Regenerate", visible=True, min_width=120)upload_btn = gr.UploadButton("π Upload image", file_types=["image"], visible=False, min_width=120)with gr.Accordion("Advanced settings", open=False, visible=True99 unmodified linesinputs=decoding_strategy,outputs=top_p,)with gr.Column(scale=5) as result_area:generated_memes_gallery = gr.Gallery(# value="Images generated will appear here",label="IDEFICS Generated Memes",1 unmodified lineelem_id="generated_memes_gallery",show_download_button=True,show_share_button=True,columns=[2],object_fit="contain",height=428) #height 600 when expandedwith gr.Row(equal_height=True):with gr.Box(elem_id="gallery_box"):gallery_type_choice = gr.Radio(13 unmodified lines# value= value given by gallery_type_choice,label="Templates Gallery",allow_preview=False,columns=6,elem_id="gallery",show_share_button=False,height=400,136 unmodified lines# yield "", None, chat_historyfull_text += acc_textacc_text = ""gr.on(triggers=[textbox.submit,imagebox.upload,submit_btn.click],fn=expand_layout,outputs=[upload_area, generated_memes_gallery],queue=False).then(fn=lambda: "", inputs=[], outputs=[generated_memes_gallery], queue=False).then(fn=model_inference,inputs=[model_selector,10 unmodified linestext_at_the_top,font_meme_text,],outputs=[textbox, generated_memes_gallery, chatbot],)def remove_last_turn(chat_history):10 unmodified linesfn=remove_last_turn,inputs=chatbot,outputs=[chatbot, textbox, generated_memes_gallery],queue=False).then(fn=model_inference,inputs=[20 unmodified linesupload_btn.upload(add_file, [upload_btn], [imagebox, upload_btn], queue=False)submit_btn.click(lambda: gr.update(label="π Upload image", interactive=True), [], upload_btn, queue=False)textbox.submit(lambda: gr.update(label="π Upload image", interactive=True), [], upload_btn, queue=False)clear_btn.click(lambda: gr.update(label="π Upload image", interactive=True), [], upload_btn, queue=False)gallery_type_choice.change(fn=choose_gallery,5 unmodified linesfn=add_file_gallery,inputs=[template_gallery],outputs=[textbox, imagebox, generated_memes_gallery],).success(fn=expand_layout,outputs=[upload_area, generated_memes_gallery],queue=False).success(fn=model_inference,inputs=[18 unmodified lines],)demo.load(fn=choose_gallery, inputs=[gallery_type_choice], outputs=[template_gallery], queue=False)demo.queue(concurrency_count=40, max_size=40)demo.launch()
app_dialogue.py+109-134