Spaces:
Runtime error
Runtime error
Merge pull request #21 from barun-saha/visual
Browse filesFiles changed (6)
31 unmodified lines3233343536353637383931 unmodified lines PRELOAD_DATA_FILE = 'examples/example_02.json' SLIDES_TEMPLATE_FILE = 'langchain_templates/template_combined.txt' # JSON_TEMPLATE_FILE = 'langchain_templates/text_to_json_template_02.txt' INITIAL_PROMPT_TEMPLATE = 'langchain_templates/chat_prompts/initial_template_v3_two_cols.txt' REFINEMENT_PROMPT_TEMPLATE = 'langchain_templates/chat_prompts/refinement_template_v3_two_cols.txt' INITIAL_PROMPT_TEMPLATE = 'langchain_templates/chat_prompts/initial_template_v4_two_cols_img.txt' REFINEMENT_PROMPT_TEMPLATE = 'langchain_templates/chat_prompts/refinement_template_v4_two_cols_img.txt'
PPTX_TEMPLATE_FILES = { 'Basic': {123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""Search photos using Pexels API."""import osimport randomfrom io import BytesIOfrom typing import Union, Tuple, Optionalfrom urllib.parse import urlparse, parse_qs
import requests
REQUEST_TIMEOUT = 12MAX_PHOTOS = 2
def search_pexels(query: str, size: Optional[str] = 'medium', per_page: int = MAX_PHOTOS): """ Searches for images on Pexels using the provided query.
This function sends a GET request to the Pexels API with the specified search query and authorization header containing the API key. It returns the JSON response from the API.
:param query: The search query for finding images. :param size: The size of the images: small, medium, or large. :param per_page: No. of results to be displayed per page. :return: The JSON response from the Pexels API containing search results. :raises requests.exceptions.RequestException: If the request to the Pexels API fails. """
url = 'https://api.pexels.com/v1/search' headers = { 'Authorization': os.getenv('PEXEL_API_KEY') } params = { 'query': query, 'size': size, 'page': 1, 'per_page': per_page } response = requests.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT) response.raise_for_status() # Ensure the request was successful
return response.json()
def get_photo_url_from_api_response( json_response: dict) -> Tuple[Union[str, None], Union[str, None]]: """ Return a randomly chosen photo from a Pexels search API response. In addition, also return the original URL of the page on Pexels.
:param json_response: The JSON response. :return: The selected photo URL and page URL or `None`. """
page_url = None photo_url = None
if 'photos' in json_response: photos = json_response['photos']
if photos: photo_idx = random.choice(list(range(MAX_PHOTOS))) photo = photos[photo_idx]
if 'url' in photo: page_url = photo['url']
if 'src' in photo: if 'large' in photo['src']: photo_url = photo['src']['large'] elif 'original' in photo['src']: photo_url = photo['src']['original']
return photo_url, page_url
def get_image_from_url(url: str) -> BytesIO: """ Fetches an image from the specified URL and returns it as a BytesIO object.
This function sends a GET request to the provided URL, retrieves the image data, and wraps it in a BytesIO object, which can be used like a file.
:param url: The URL of the image to be fetched. :return: A BytesIO object containing the image data. :raises requests.exceptions.RequestException: If the request to the URL fails. """
response = requests.get(url, stream=True, timeout=REQUEST_TIMEOUT) response.raise_for_status() image_data = BytesIO(response.content)
return image_data
def extract_dimensions(url: str) -> Tuple[int, int]: """ Extracts the height and width from the URL parameters.
:param url: The URL containing the image dimensions. :return: A tuple containing the width and height as integers. """ parsed_url = urlparse(url) query_params = parse_qs(parsed_url.query) width = int(query_params.get('w', [0])[0]) height = int(query_params.get('h', [0])[0])
return width, height10 unmodified lines1112131415161742 unmodified lines6061626263646566676869707110 unmodified lines
HF_API_URL = f"https://api-inference.huggingface.co/models/{GlobalConfig.HF_LLM_MODEL_NAME}"HF_API_HEADERS = {"Authorization": f"Bearer {GlobalConfig.HUGGINGFACEHUB_API_TOKEN}"}REQUEST_TIMEOUT = 35
logger = logging.getLogger(__name__)
42 unmodified lines """
try: response = http_session.post(HF_API_URL, headers=HF_API_HEADERS, json=payload, timeout=15) response = http_session.post( HF_API_URL, headers=HF_API_HEADERS, json=payload, timeout=REQUEST_TIMEOUT ) result = response.json() except requests.exceptions.Timeout as te: logger.error('*** Error: hf_api_query timeout! %s', str(te))123456789561011121314151617181920212223242526272829303 unmodified lines3435363738394025262728293031323334353637383940414142433 unmodified lines474849505152535354555611 unmodified lines686970717172737491 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219325 unmodified lines219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399214 unmodified lines614615616617618619620621622623624625626627628629630423631632633426634635428429430431636637638639433640641642643436644645438646647648440441442443444649650651446652653654448655656657658451659660453454455456457458459661662663664665666667668669670671672673674675676677678461462679680681682683684685686687688689690691692693694695696697464698699700701467702703469470471472473704705706707475708709710711478712713714715716717718719720721722723724481725726483484485727728729730731489732733491492493734735736737738497498499500501502503504505506507739740741742510743744512513514515745746747748517749750751752520753754522523755756757758525759760761762763"""A set of functions to create a PowerPoint slide deck."""import loggingimport pathlibimport randomimport reimport sysimport tempfile
from typing import List, Tuplefrom typing import List, Tuple, Optional
import json5import pptxfrom dotenv import load_dotenvfrom pptx.enum.shapes import MSO_AUTO_SHAPE_TYPEfrom pptx.shapes.placeholder import PicturePlaceholder, SlidePlaceholder
sys.path.append('..')sys.path.append('../..')
import helpers.image_search as imsfrom global_config import GlobalConfig
load_dotenv()
# English Metric Unit (used by PowerPoint) to inchesEMU_TO_INCH_SCALING_FACTOR = 1.0 / 914400INCHES_1_5 = pptx.util.Inches(1.5)3 unmodified linesINCHES_0_3 = pptx.util.Inches(0.3)
STEP_BY_STEP_PROCESS_MARKER = '>> 'IMAGE_DISPLAY_PROBABILITY = 0.3FOREGROUND_IMAGE_PROBABILITY = 0.75SLIDE_NUMBER_REGEX = re.compile(r"^slide[ ]+\d+:", re.IGNORECASE)
PATTERN = re.compile(r"^slide[ ]+\d+:", re.IGNORECASE)SAMPLE_JSON_FOR_PPTX = '''{ "title": "Understanding AI", "slides": [ { "heading": "Introduction", "bullet_points": [ "Brief overview of AI", [ "Importance of understanding AI" ] ] } ]}'''
logger = logging.getLogger(__name__)
3 unmodified lines Remove the slide number from a given slide header.
:param header: The header of a slide. :return: The header without slide number. """
if PATTERN.match(header): if SLIDE_NUMBER_REGEX.match(header): idx = header.find(':') header = header[idx + 1:]
11 unmodified lines :param structured_data: The presentation contents as "JSON" (may contain trailing commas). :param slides_template: The PPTX template to use. :param output_file_path: The path of the PPTX file to save as. :return A list of presentation title and slides headers. :return: A list of presentation title and slides headers. """
# The structured "JSON" might contain trailing commas, so using json591 unmodified lines :param slide_height_inch: The height of the slide in inches. """
status = False
if random.random() < IMAGE_DISPLAY_PROBABILITY: if random.random() < FOREGROUND_IMAGE_PROBABILITY: status = _handle_display_image__in_foreground( presentation, slide_json, slide_width_inch, slide_height_inch ) else: status = _handle_display_image__in_background( presentation, slide_json, slide_width_inch, slide_height_inch )
if status: return
# Image display failed, so display only text bullet_slide_layout = presentation.slide_layouts[1] slide = presentation.slides.add_slide(bullet_slide_layout)
25 unmodified lines )
def _handle_display_image__in_foreground( presentation: pptx.Presentation(), slide_json: dict, slide_width_inch: float, slide_height_inch: float) -> bool: """ Create a slide with text and image using a picture placeholder layout.
:param presentation: The presentation object. :param slide_json: The content of the slide as JSON data. :param slide_width_inch: The width of the slide in inches. :param slide_height_inch: The height of the slide in inches. :return: True if the side has been processed. """
img_keywords = slide_json['img_keywords'].strip() slide = presentation.slide_layouts[8] # Picture with Caption slide = presentation.slides.add_slide(slide)
title_placeholder = slide.shapes.title title_placeholder.text = remove_slide_number_from_heading(slide_json['heading'])
pic_col: PicturePlaceholder = slide.shapes.placeholders[1] text_col: SlidePlaceholder = slide.shapes.placeholders[2] flat_items_list = get_flat_list_of_contents(slide_json['bullet_points'], level=0)
for idx, an_item in enumerate(flat_items_list): if idx == 0: text_col.text_frame.text = an_item[0].removeprefix(STEP_BY_STEP_PROCESS_MARKER) else: paragraph = text_col.text_frame.add_paragraph() paragraph.text = an_item[0].removeprefix(STEP_BY_STEP_PROCESS_MARKER) paragraph.level = an_item[1]
if not img_keywords: # No keywords, so no image search and addition return True
try: photo_url, page_url = ims.get_photo_url_from_api_response( ims.search_pexels(query=img_keywords, size='medium') )
if photo_url: pic_col.insert_picture( ims.get_image_from_url(photo_url) )
_add_text_at_bottom( slide=slide, slide_width_inch=slide_width_inch, slide_height_inch=slide_height_inch, text='Photo provided by Pexels', hyperlink=page_url ) except Exception as ex: logger.error( '*** Error occurred while running adding image to slide: %s', str(ex) )
return True
def _handle_display_image__in_background( presentation: pptx.Presentation(), slide_json: dict, slide_width_inch: float, slide_height_inch: float) -> bool: """ Add a slide with text and an image in the background. It works just like `_handle_default_display()` but with a background image added.
:param presentation: The presentation object. :param slide_json: The content of the slide as JSON data. :param slide_width_inch: The width of the slide in inches. :param slide_height_inch: The height of the slide in inches. :return: True if the slide has been processed. """
img_keywords = slide_json['img_keywords'].strip()
# Add a photo in the background, text in the foreground slide = presentation.slides.add_slide(presentation.slide_layouts[1])
title_shape = slide.shapes.title body_shape = slide.shapes.placeholders[1] title_shape.text = remove_slide_number_from_heading(slide_json['heading'])
flat_items_list = get_flat_list_of_contents(slide_json['bullet_points'], level=0)
for idx, an_item in enumerate(flat_items_list): if idx == 0: body_shape.text_frame.text = an_item[0].removeprefix(STEP_BY_STEP_PROCESS_MARKER) else: paragraph = body_shape.text_frame.add_paragraph() paragraph.text = an_item[0].removeprefix(STEP_BY_STEP_PROCESS_MARKER) paragraph.level = an_item[1]
if not img_keywords: # No keywords, so no image search and addition return True
try: photo_url, page_url = ims.get_photo_url_from_api_response( ims.search_pexels(query=img_keywords, size='large') )
if photo_url: picture = slide.shapes.add_picture( image_file=ims.get_image_from_url(photo_url), left=0, top=0, width=pptx.util.Inches(slide_width_inch), )
_add_text_at_bottom( slide=slide, slide_width_inch=slide_width_inch, slide_height_inch=slide_height_inch, text='Photos provided by Pexels', hyperlink=page_url )
# Move picture to background # https://github.com/scanny/python-pptx/issues/49#issuecomment-137172836 slide.shapes._spTree.remove(picture._element) slide.shapes._spTree.insert(2, picture._element) except Exception as ex: logger.error( '*** Error occurred while running adding image to the slide background: %s', str(ex) )
return True
def _add_text_at_bottom( slide: pptx.slide.Slide, slide_width_inch: float, slide_height_inch: float, text: str, hyperlink: Optional[str] = None, target_height: Optional[float] = 0.5): """ Add arbitrary text to a textbox positioned near the lower left side of a slide.
:param slide: The slide. :param slide_width_inch: The width of the slide. :param slide_height_inch: The height of the slide. :param target_height: the target height of the box in inches (optional). :param text: The text to be added :param hyperlink: The hyperlink to be added to the text (optional). """
footer = slide.shapes.add_textbox( left=INCHES_1, top=pptx.util.Inches(slide_height_inch - target_height), width=pptx.util.Inches(slide_width_inch), height=pptx.util.Inches(target_height) )
paragraph = footer.text_frame.paragraphs[0] run = paragraph.add_run() run.text = text run.font.size = pptx.util.Pt(10) run.font.underline = False
if hyperlink: run.hyperlink.address = hyperlink
def _handle_double_col_layout( presentation: pptx.Presentation(), slide_json: dict,214 unmodified lines return slide_width_inch, slide_height_inch
def print_placeholder_names(slide: pptx.slide.Slide): """ Display the placeholder details of a given slide.
:param slide: The slide. """
for shape in slide.placeholders: print(f'{shape.placeholder_format.idx=}, {shape.name=}')
if __name__ == '__main__': _JSON_DATA = ''' { "title": "Understanding AI", "title": "Mastering PowerPoint Shapes", "slides": [ { "heading": "Introduction", "heading": "Introduction to PowerPoint Shapes", "bullet_points": [ "Brief overview of AI", [ "Importance of understanding AI" ] "Shapes are fundamental elements in PowerPoint", "Used to create diagrams, flowcharts, and visuals", "Available in various types: lines, rectangles, circles, etc." ], "key_message": "" "key_message": "", "img_keywords": "PowerPoint shapes, basic shapes" }, { "heading": "What is AI?", "heading": "Types of Shapes in PowerPoint", "bullet_points": [ "Definition of AI", "Lines: Connect two points", "Rectangles: Four-sided figures with right angles", [ "Types of AI", [ "Narrow or weak AI", "General or strong AI" ] "Squares: Special type of rectangle with equal sides", "Rounded Rectangles: Rectangles with rounded corners" ], "Differences between AI and machine learning" "Circles: Round shapes with no corners", "Ovals: Elliptical shapes" ], "key_message": "" "key_message": "", "img_keywords": "PowerPoint shapes, types of shapes" }, { "heading": "How AI Works", "heading": "Creating and Manipulating Shapes", "bullet_points": [ "Overview of AI algorithms", [ "Types of AI algorithms", [ "Rule-based systems", "Decision tree systems", "Neural networks" ">> Select the 'Home' tab and click on 'Shapes'", ">> Choose the desired shape", ">> Click and drag to create the shape", ">> Resize, move, or rotate shapes using handles", ">> Change shape color, fill, and outline" ], "key_message": "Demonstrates the process of creating and manipulating shapes", "img_keywords": "PowerPoint shapes, creating shapes, manipulating shapes" }, { "heading": "Advanced Shape Manipulation", "bullet_points": [ { "heading": "Adding Text to Shapes", "bullet_points": [ "Right-click on the shape and select 'Add Text'", "Type or paste the desired text" ] ], "How AI processes data" }, { "heading": "Grouping and Ungrouping Shapes", "bullet_points": [ "Select multiple shapes and press 'Ctrl + G' to group", "Right-click and select 'Ungroup' to separate" ] } ], "key_message": "Explores advanced techniques for working with shapes", "img_keywords": "PowerPoint shapes, advanced manipulation, grouping, text in shapes" }, { "heading": "Using the 'Format' Tab for Shapes", "bullet_points": [ "Access advanced shape formatting options", "Change shape fill, outline, and effects", "Adjust shape size and position" ], "key_message": "" "key_message": "", "img_keywords": "PowerPoint shapes, format tab, advanced formatting" }, { "heading": "Building AI Models", "heading": "Example: Creating a Simple Diagram", "bullet_points": [ ">> Collect data", ">> Select model or architecture to use", ">> Set appropriate parameters", ">> Train model with data", ">> Run inference", "Use rectangles to represent blocks", "Use lines to connect blocks", "Add text to shapes to label elements" ], "key_message": "" "key_message": "Illustrates the use of shapes to create a simple diagram", "img_keywords": "PowerPoint shapes, diagram example, simple diagram" }, { "heading": "Pros and Cons: Deep Learning vs. Classical Machine Learning", "heading": "Example: Creating a Flowchart", "bullet_points": [ "Use different shapes to represent steps, decisions, and inputs/outputs", "Use connectors to link shapes", "Add text to shapes to describe each step" ], "key_message": "Demonstrates the use of shapes to create a flowchart", "img_keywords": "PowerPoint shapes, flowchart example, creating flowchart" }, { "heading": "Double Column Layout: Shapes in Older vs. Newer PowerPoint Versions", "bullet_points": [ { "heading": "Classical Machine Learning", "heading": "Older PowerPoint Versions", "bullet_points": [ "Interpretability: Easy to understand the model", "Faster Training: Quicker to train models", "Scalability: Can handle large datasets" "Limited shape types and formatting options", "Less intuitive shape creation and manipulation" ] }, { "heading": "Deep Learning", "heading": "Newer PowerPoint Versions", "bullet_points": [ "Handling Complex Data: Can learn from raw data", "Feature Extraction: Automatically learns features", "Improved Accuracy: Achieves higher accuracy" "Expanded shape library with more types and styles", "Improved shape formatting and manipulation tools" ] } ], "key_message": "" }, { "heading": "Pros of AI", "bullet_points": [ "Increased efficiency and productivity", "Improved accuracy and precision", "Enhanced decision-making capabilities", "Personalized experiences" ], "key_message": "AI can be used for many different purposes" "key_message": "Compares the use of shapes in older and newer PowerPoint versions", "img_keywords": "PowerPoint shapes, older versions, newer versions, comparison" }, { "heading": "Cons of AI", "heading": "Tips for Effective Use of Shapes", "bullet_points": [ "Job displacement and loss of employment", "Bias and discrimination", "Privacy and security concerns", "Dependence on technology" "Keep shapes simple and uncluttered", "Use consistent colors and styles", "Avoid overusing shapes, maintain balance with text and other elements" ], "key_message": "" "key_message": "Provides best practices for using shapes in presentations", "img_keywords": "PowerPoint shapes, best practices, effective use" }, { "heading": "Future Prospects of AI", "heading": "Conclusion", "bullet_points": [ "Advancements in fields such as healthcare and finance", "Increased use" "Shapes are versatile tools in PowerPoint", "Mastering shapes enhances presentation visuals", "Practice and experimentation are key to improving shape usage" ], "key_message": "" "key_message": "Summarizes the importance of shapes in PowerPoint and encourages practice", "img_keywords": "PowerPoint shapes, conclusion, importance" } ]}'''1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586You are a helpful, intelligent chatbot. You are experienced with PowerPoint.
Create the slides for a presentation on the given topic.Include main headings for each slide, detailed bullet points for each slide.Add relevant content to each slide.The content of each slide should be VERBOSE, DESCRIPTIVE, and very DETAILED.If relevant, add one or two EXAMPLES to illustrate the concept.For two or three important slides, generate the key message that those slides convey.Identify if a slide describes a step-by-step/sequential process, then begin the bullet points with a special marker >>. Limit this to max two or three slides.Also, add at least one slide with a double column layout by generating appropriate content based on the description in the JSON schema provided below.In addition, for each slide, add image keywords based on the content of the respective slides.These keywords will be later used to search for images from the Web relevant to the slide content.ALWAYS add a concluding slide at the end, containing a list of the key takeaways and an optional call-to-action if relevant to the context.Unless explicitly instructed, create 10 TO 12 SLIDES in total.
### Topic:{question}
The output must be only a valid and syntactically correct JSON adhering to the following schema:{{ "title": "Presentation Title", "slides": [ {{ "heading": "Heading for the First Slide", "bullet_points": [ "First bullet point", [ "Sub-bullet point 1", "Sub-bullet point 2" ], "Second bullet point" ], "key_message": "", "img_keywords": "a few keywords" }}, {{ "heading": "Heading for the Second Slide", "bullet_points": [ "First bullet point", "Second bullet item", "Third bullet point" ], "key_message": "The key message conveyed in this slide", "img_keywords": "some keywords for this slide" }}, {{ "heading": "A slide that describes a step-by-step/sequential process", "bullet_points": [ ">> The first step of the process (begins with special marker >>)", ">> A second step (begins with >>)", ">> Third step", ], "key_message": "", "img_keywords": "" }}, {{ "heading": "A slide with a double column layout (useful for side-by-side comparison/contrasting of two related concepts, e.g., pros & cons, advantages & risks, old approach vs. modern approach, and so on)", "bullet_points": [ {{ "heading": "Heading of the left column", "bullet_points": [ "First bullet point", "Second bullet item", "Third bullet point" ] }}, {{ "heading": "Heading of the right column", "bullet_points": [ "First bullet point", "Second bullet item", "Third bullet point" ] }} ], "key_message": "", "img_keywords": "" }} ]}}
### Output:```json1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192You are a helpful, intelligent chatbot. You are experienced with PowerPoint.
A list of user instructions is provided below in sequential order -- from the oldest to the latest.The previously generated content of the slide deck in JSON format is also provided.Follow the instructions to revise the content of the previously generated slides of the presentation on the given topic.Include main headings for each slide, detailed bullet points for each slide.Add relevant content to each slide.The content of each slide should be VERBOSE, DESCRIPTIVE, and very DETAILED.If relevant, add one or two EXAMPLES to illustrate the concept.For two or three important slides, generate the key message that those slides convey.Identify if a slide describes a step-by-step/sequential process, then begin the bullet points with a special marker >>. Limit this to max two or three slides.Also, add at least one slide with a double column layout by generating appropriate content based on the description in the JSON schema provided below.In addition, for each slide, add image keywords based on the content of the respective slides.These keywords will be later used to search for images from the Web relevant to the slide content.ALWAYS add a concluding slide at the end, containing a list of the key takeaways and an optional call-to-action if relevant to the context.Unless explicitly instructed, create 10 TO 12 SLIDES in total.
### List of instructions:{instructions}
### Previously generated slide deck content as JSON:{previous_content}
The output must be only a valid and syntactically correct JSON adhering to the following schema:{{ "title": "Presentation Title", "slides": [ {{ "heading": "Heading for the First Slide", "bullet_points": [ "First bullet point", [ "Sub-bullet point 1", "Sub-bullet point 2" ], "Second bullet point" ], "key_message": "", "img_keywords": "a few keywords" }}, {{ "heading": "Heading for the Second Slide", "bullet_points": [ "First bullet point", "Second bullet item", "Third bullet point" ], "key_message": "The key message conveyed in this slide", "img_keywords": "some keywords for this slide" }}, {{ "heading": "A slide that describes a step-by-step/sequential process", "bullet_points": [ ">> The first step of the process (begins with special marker >>)", ">> A second step (begins with >>)", ">> Third step", ], "key_message": "", "img_keywords": "" }}, {{ "heading": "A slide with a double column layout (useful for side-by-side comparison/contrasting of two related concepts, e.g., pros & cons, advantages & risks, old approach vs. modern approach, and so on)", "bullet_points": [ {{ "heading": "Heading of the left column", "bullet_points": [ "First bullet point", "Second bullet item", "Third bullet point" ] }}, {{ "heading": "Heading of the right column", "bullet_points": [ "First bullet point", "Second bullet item", "Third bullet point" ] }} ], "key_message": "", "img_keywords": "" }} ]}}
### Output:```jsonglobal_config.py+2-2
helpers/image_search.pyAdded+111
helpers/llm_helper.py+7-1
helpers/pptx_helper.py+320-85
langchain_templates/chat_prompts/initial_template_v4_two_cols_img.txtAdded+86
langchain_templates/chat_prompts/refinement_template_v4_two_cols_img.txtAdded+92