Skip to main content

Integrating API

In this section, we'll discuss how to integrate the Gmail API and the OpenAI API to make these two functionalities work together.

Main Program

Let's first take a look at the structure of the main program:

from argparse import ArgumentParser
from datetime import datetime, timedelta

from gmail_api import build_service, get_messages, parse_message
from openai_api import chatgpt_summary
from tqdm import tqdm


def generate_markdown_report(input_text, project_name, date):
title = f"{project_name} Update Report - {date}"
markdown_text = input_text.replace('\n', '\n\n')
markdown_content = f"# {title}\n\n{markdown_text}"
file_name = f"{project_name}-update-{date}.md"
with open(file_name, "w", encoding="utf-8") as file:
file.write(markdown_content)
return file_name


def main(project_name, time_length):

current_date = datetime.now()
after_date = current_date - timedelta(days=time_length)
after_date = after_date.strftime('%Y/%m/%d')

service = build_service()
messages = get_messages(
service,
after_date=after_date,
subject_filter=project_name
)

results = [
parse_message(service, msg['id'])
for msg in tqdm(messages)
]

# Call OpenAI API
summary = chatgpt_summary(results)
summary = f'{summary}\n\n---\n\nThe above report was automatically generated by OpenAI GPT-3.5 Turbo model.'

# Generate Markdown report
markdown_file = generate_markdown_report(
summary, project_name, current_date.strftime('%Y-%m-%d'))
print(f"Markdown file generated: {markdown_file}")


if __name__ == "__main__":
parser = ArgumentParser(description="Generate a project update report.")
parser.add_argument(
"--project_name",
type=str,
help="The name of the project to track.",
default="Albumentations"
)
parser.add_argument(
"--time_length",
type=int,
help="The time length (in days) to track updates.",
default=1
)

args = parser.parse_args()

main(args.project_name, args.time_length)

Introduction to the Main Program

1. Importing Modules

At the beginning of the program, necessary Python modules and custom functions are imported:

  • ArgumentParser for parsing command-line arguments.
  • datetime and timedelta for handling date and time calculations.
  • build_service, get_messages, parse_message for handling Gmail API operations.
  • chatgpt_summary for invoking the OpenAI API to generate summaries of email contents.
  • tqdm for displaying progress bars.

2. Generating Reports

The generate_markdown_report function is responsible for generating Markdown-formatted report files:

  • It takes input_text (summary of email content), project_name (name of the project), and date as parameters.
  • It replaces newline characters in input_text with Markdown line breaks.
  • It generates the title and content of the Markdown file, then writes it to a .md file named based on the project name and date.

3. Main Program

The main program executes the following steps:

  • Sets the current date and past date (calculated based on the time_length parameter).
  • Builds the Gmail API service using the build_service function.
  • Calls get_messages to retrieve emails containing the specified project name since the specified date.
  • Uses tqdm to display a progress bar for email parsing.
  • Parses the content of each email and sends it to the OpenAI API for summarization.
  • Adds the summary content to a Markdown file and generates that file.

4. Command-Line Argument Handling

In the input section, the program parses two command-line arguments:

  • --project_name: The name of the project specified by the user, defaulting to "Albumentations".
  • --time_length: The length of time (in days) to track updates, defaulting to 1 day.

These parameters allow users to customize the project name and duration for generating reports.