Skip to content

Commit

Permalink
fix: minor fixes to get it running locally again
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelfromyeg committed Aug 13, 2024
1 parent bc87cca commit 7493db3
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 27 deletions.
10 changes: 9 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
HOST=0.0.0.0
PORT=5000

FLASK_APP=bereal/server.py
FLASK_ENV=development
SECRET_KEY=

SECRET_KEY=hello

HOST=redis
PORT=5000

REDIS_HOST=redis
REDIS_PORT=6379

TWILIO_PHONE_NUMBER=+11234567890
TWILIO_AUTH_TOKEN=asdf
TWILIO_ACCOUNT_SID=1234
52 changes: 45 additions & 7 deletions bereal/bereal.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,35 @@
from .logger import logger
from .utils import BASE_URL, CONTENT_PATH, TIMEOUT, str2datetime

from typing import TypedDict, Literal


class MediaInfo(TypedDict):
"""
A media object in a BeReal API response.
"""

url: str
width: int
height: int
mediaType: Literal["image"]


class BeRealPost(TypedDict):
"""
The response from the 'memories' endpoint.
"""

memoryDay: str
momentId: str
mainPostMemoryId: str
mainPostThumbnail: MediaInfo
mainPostPrimaryMedia: MediaInfo
mainPostSecondaryMedia: MediaInfo
mainPostTakenAt: str
isLate: bool
numPostsForMoment: int


def send_code(phone: str) -> Any | None:
"""
Expand All @@ -32,10 +61,14 @@ def send_code(phone: str) -> Any | None:
logger.info("Request successful!")

response_json = response.json()
if "data" in response_json and "otpSession" in response_json["data"]:
return response_json["data"]["otpSession"]
if (
"data" in response_json
and "otpSession" in response_json["data"]
and "sessionInfo" in response_json["data"]["otpSession"]
):
return response_json["data"]["otpSession"]["sessionInfo"]
else:
logger.warning("No 'otpSession' found in the response!")
logger.warning("No 'sessionInfo' found in the response!")
return None
case _:
logger.warning("Request failed with status code: %s", response.status_code)
Expand Down Expand Up @@ -85,8 +118,9 @@ def memories(phone: str, year: str, token: str, sdate: datetime, edate: datetime
data_array: list[Any] = []

if response.status_code == 200:
response_data = response.json().get("data", {})
data_array = response_data.get("data", [])
response_json = response.json()
logger.debug("memories", response_json)
data_array: list[BeRealPost] = response_json["data"].get("data", [])
else:
logger.warning("Request failed with status code %s", response.status_code)
return False
Expand Down Expand Up @@ -119,16 +153,20 @@ def download_image(date_str: str, url: str, base_path: str) -> None:
"Failed to download %s with code %d; will continue", image_name, img_response.status_code
)

if len(data_array) == 0:
logger.warning("No data found in the response!")
return False

# iterate through the response and download images
for item in data_array:
logger.debug("Processing %s", item)

date_str = item.get("memoryDay", "")

primary_image_url = item["primary"].get("url", "")
primary_image_url = item["mainPostPrimaryMedia"].get("url", "")
download_image(date_str, primary_image_url, primary_path)

secondary_image_url = item["secondary"].get("url", "")
secondary_image_url = item["mainPostSecondaryMedia"].get("url", "")
download_image(date_str, secondary_image_url, secondary_path)

return True
1 change: 1 addition & 0 deletions bereal/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ def str2mode(s: str | None) -> Mode:
REDIS_HOST: str | None = os.getenv("REDIS_HOST") or "redis"
REDIS_PORT: str | None = os.getenv("REDIS_PORT") or "6379"
REDIS_PORT = int(REDIS_PORT) if REDIS_PORT is not None else None
logger.info("REDIS_HOST: %s, REDIS_PORT: %s", REDIS_HOST, REDIS_PORT)

TIMEOUT = config.getint("bereal", "timeout", fallback=10)
IMAGE_QUALITY = config.getint("bereal", "image_quality", fallback=50)
Expand Down
3 changes: 3 additions & 0 deletions bereal/videos.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ def create_slideshow3(
raise ValueError("Music file does not exist!")

n_images = len(os.listdir(input_folder))
if n_images == 0:
raise ValueError("No images found in input folder!")

if len(timestamps) < n_images:
additional_needed = n_images - len(timestamps)

Expand Down
33 changes: 14 additions & 19 deletions client/src/components/Processing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,7 @@ const VideoProcessor: React.FC<Props> = (props: Props) => {
if (response.status === 401) {
setError("Please refresh the page and try again.");
setStage("phoneInput");
return;
}

if (response.status > 299) {
} else if (response.status > 299) {
console.warn("Couldn't check progress:", response);
console.log("Progress unknown... continuing anyway!");

Expand All @@ -48,23 +45,21 @@ const VideoProcessor: React.FC<Props> = (props: Props) => {
setError("Failed to generate video. Try again later.");
setStage("phoneInput");
}
} else {
const { status, result } = response.data;

return;
}

const { status, result } = response.data;

if (status === "FAILURE") {
setError("Failed to generate video. Try again later.");
setStage("phoneInput");
}
if (status === "SUCCESS") {
setProgress(100);
if (status === "FAILURE") {
setError("Failed to generate video. Try again later.");
setStage("phoneInput");
}
if (status === "SUCCESS") {
setProgress(100);

setResult(result);
setStage("videoDisplay");
} else {
setProgress(logProgress(response.data));
setResult(result);
setStage("videoDisplay");
} else {
setProgress(logProgress(response.data));
}
}
} catch (error) {
// again, not something the user needs to know about; just try again
Expand Down

0 comments on commit 7493db3

Please sign in to comment.