Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IEEE- Message Formatter #1

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
159 changes: 146 additions & 13 deletions format_google_chats.ipynb

Large diffs are not rendered by default.

44 changes: 44 additions & 0 deletions format_google_chats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from handlers.pdf_handler import PDFHandler
from tasks import process_messages
from tasks import load_file
import logging
import sys

logging.basicConfig(level=logging.INFO) # Set to DEBUG for more verbose logging

### FILE CONFIGURATION ###

pdf_path = "sample_messages/messages_more_pages.json"
file_name = "sample_output.pdf"
subtitle = "CIVIC TECH ATLANTA"

message_source = "google_chats"

initial_y_position = 800
maximum_y_position = 100

logging.debug("Inital variables set. Logs below are from the main function.")

if __name__ == "__main__":

file_data_raw = load_file(path=pdf_path)
messages = file_data_raw.get("messages", [])

pdf_handler = PDFHandler(
pdf_path=pdf_path,
file_name=file_name,
subtitle=subtitle,
init_y_position=initial_y_position,
maximum_y_position=maximum_y_position)

try:
process_messages(
messages=messages,
message_source=message_source,
pdf_handler=pdf_handler)
except Exception as e:
logging.error(f"Error Occurred : {e}")
finally:
pdf_handler.pdf.save()
logging.info(f"PDF saved successfully with name : {file_name}")
sys.exit(0)
35 changes: 35 additions & 0 deletions handlers/base_message_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from abc import ABC
from handlers.pdf_handler import PDFHandler
from datetime import datetime

from typing import Final


class BaseMessageHandler(ABC):

gm_text_vertical_spacing : Final[int] = 20
gm_image_height_limit : Final[int] = 200

def __init__(self, pdf_handler : PDFHandler, message : dict[str, str]) -> None:
self.pdf_handler = pdf_handler
self.message = message

def handle_pagination(self) -> None:
if self.pdf_handler.pos_y < self.pdf_handler.maximum_y_position:
self.pdf_handler.pdf.showPage()
self.pdf_handler.pos_y = self.pdf_handler.init_y_position

def transform_datetime(self, datetime_str: str, dt_format : str = "%A, %B %d, %Y at %I:%M:%S %p %Z") -> str:
"""
Transform a datetime string to a datetime object and then to an ISO 8601 string.

The dt_format default value comes from google messages' datetime format. Other message sources may require a different format.

The default is : "%A, %B %d, %Y at %I:%M:%S %p %Z"
"""
dt = datetime.strptime(datetime_str, dt_format)
return dt.isoformat()

def process_message(self) -> bool:
raise NotImplementedError("Subclasses must implement this method")

32 changes: 32 additions & 0 deletions handlers/google_message_handler/gm_image_message_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from handlers.base_message_handler import BaseMessageHandler
from handlers.pdf_handler import PDFHandler
from reportlab.lib.colors import black

import logging

class GoogleMessagesImageHandler(BaseMessageHandler):
def __init__(self, pdf_handler : PDFHandler, message : dict[str, str]) -> None:
super().__init__(pdf_handler=pdf_handler, message=message)


def process_message(self) -> bool:
image_url = self.message["annotations"][0]["url_metadata"]["image_url"]
text_handler = self.pdf_handler.pdf.beginText(40, self.pdf_handler.pos_y)
text_handler.setFont("Courier", 10)
text_handler.setFillColor(black)
author_name = self.message["creator"]["name"]
author_mail = self.message["creator"]["email"]
formatted_text = f"""({(self.transform_datetime(datetime_str=self.message["created_date"]))}) {author_name} - {author_mail} :(IMAGE BELOW)"""
text_handler.textLine(formatted_text)
self.pdf_handler.pdf.drawText(text_handler)
logging.info(f"image_url : {image_url} ")
self.pdf_handler.pos_y -= self.gm_text_vertical_spacing

logging.info(f"CURRENT POS Y : {self.pdf_handler.pos_y}")
image_y_pos = -(self.gm_image_height_limit - self.pdf_handler.pos_y)
result = self.pdf_handler.pdf.drawImage(image_url, 150, image_y_pos, height=self.gm_image_height_limit, preserveAspectRatio=True)
logging.info(f"result : {result}")
self.pdf_handler.pos_y -= 220
logging.info(f"POS Y After : {self.pdf_handler.pos_y}")
self.handle_pagination()
return True
43 changes: 43 additions & 0 deletions handlers/google_message_handler/gm_text_message_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from handlers.base_message_handler import BaseMessageHandler
from reportlab.lib.colors import black
from handlers.pdf_handler import PDFHandler
from reportlab.pdfbase.pdfmetrics import stringWidth

import logging

class GoogleMessagesTextHandler(BaseMessageHandler):

def __init__(self, pdf_handler : PDFHandler, message : dict[str, str]) -> None:
super().__init__(pdf_handler=pdf_handler, message=message)

def wrap_text(self, text: str, max_width: int = 520) -> list[str]:
words = text.split()
lines = []
current_line = ""
for word in words:
if stringWidth(current_line + word, "Courier", 10) <= max_width:
current_line += word + " "
else:
lines.append(current_line.strip())
current_line = word + " "
if current_line:
lines.append(current_line.strip())
return lines

def process_message(self) -> None:
author_name = self.message["creator"]["name"]
author_mail = self.message["creator"]["email"]
formatted_text = f"""({(self.transform_datetime(datetime_str=self.message["created_date"]))}) {author_name} - {author_mail} : {self.message["text"]}"""

wrapped_lines = self.wrap_text(formatted_text, 520)

for line in wrapped_lines:
logging.info(f"wrapped_line : {line}")
text_handler = self.pdf_handler.pdf.beginText(40, self.pdf_handler.pos_y)
text_handler.setFont("Courier", 10)
text_handler.setFillColor(black)
text_handler.textLine(line)
self.pdf_handler.pdf.drawText(text_handler)
self.pdf_handler.pos_y -= self.gm_text_vertical_spacing
self.handle_pagination()
return True
21 changes: 21 additions & 0 deletions handlers/pdf_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from reportlab.pdfgen import canvas

class PDFHandler:
def __init__(
self,
pdf_path : str,
file_name : str,
subtitle : str,
init_y_position : int,
maximum_y_position : int
) -> None:
self.pdf_path = pdf_path
self.init_y_position = init_y_position
pdf = canvas.Canvas(file_name)
pdf.setFillColorRGB(0, 0, 255)
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, self.init_y_position, subtitle)
pdf.line(30, self.init_y_position, 550, self.init_y_position)
self.pos_y = ( init_y_position - 20)
self.pdf = pdf
self.maximum_y_position = maximum_y_position
11 changes: 11 additions & 0 deletions handlers/unsupported_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from handlers.base_message_handler import BaseMessageHandler
from handlers.pdf_handler import PDFHandler
import logging

class UnsupportedHandler(BaseMessageHandler):
def __init__(self, pdf_handler : PDFHandler, message : dict[str, str]) -> None:
pass

def process_message(self) -> bool:
logging.info("This message has an unsupported type. Cannot output the current message.")
return False
Binary file removed output.pdf
Binary file not shown.
45 changes: 45 additions & 0 deletions output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
###################################
Tuesday, August 20, 2024
Jake Derry: this is a message

Jake Derry:

Jake Derry: this is actually a thread

Jake Derry: this is a thread
[IN REPLY TO]: "" from Jake Derry

Jake Derry: another reply
[IN REPLY TO]: "this is a thread" from Jake Derry

Jake Derry: Updated room membership.

Jake Derry: Updated room membership.

K Tokuda: Updated room membership.

K Tokuda: and a reply from someone new
[IN REPLY TO]: "another reply" from Jake Derry

Dillon Wintz: Updated room membership.

Jake Derry: Updated room membership.

Dillon Wintz: Hello everyone

K Tokuda: and a reply to my own reply
[IN REPLY TO]: "and a reply from someone new" from K Tokuda

Jake Derry: replying agin
[IN REPLY TO]: "and a reply from someone new" from K Tokuda

Dillon Wintz: yet another reply
[IN REPLY TO]: "and a reply from someone new" from K Tokuda

Jake Derry: create thread on a reply

Derrick Zhen: Updated room membership.

Dillon Wintz:

Dillon Wintz: 🤠
File renamed without changes.
Loading