from flask import Flask, render_template from datetime import datetime import os import re app = Flask(__name__) def get_dates_from_images(image_directory): # Regular expression to match files with a date format YYYY-MM-DD date_pattern = re.compile(r'(\d{4}-\d{2}-\d{2})') # List to store the dates dates = [] # Iterate over each file in the images directory for filename in os.listdir(image_directory): # Search for the pattern in the filename match = date_pattern.search(filename) if match: # Extract the date from the filename try: date = datetime.strptime(match.group(), '%Y-%m-%d') dates.append(date) except ValueError: # If the date format is incorrect, ignore the file continue # Return the sorted list of dates return sorted(dates) def get_image_and_text_for_date(date, image_directory, text_directory): formatted_date = date.strftime('%Y-%m-%d') image_file = None text_content = None # Check for image file for ext in ['jpg', 'jpeg', 'png']: # Check using full path, but store relative path for HTML image_full_path = os.path.join(image_directory, f"{formatted_date}.{ext}") if os.path.isfile(image_full_path): # Store the relative path from within the 'static' directory image_file = f"images/{formatted_date}.{ext}" break # Check for text file text_path = os.path.join(text_directory, f"{formatted_date}.txt") if os.path.isfile(text_path): with open(text_path, 'r') as file: text_content = file.read() return image_file, text_content @app.route('/') def calendar(): BASE_DIR = os.path.dirname(os.path.abspath(__file__)) image_directory = os.path.join(BASE_DIR, 'static', 'images') text_directory = os.path.join(BASE_DIR, 'texts') # Get sorted dates from image files dates = get_dates_from_images(image_directory) if not dates: return "No images found with the correct date format in the name.", 404 # Generate data for each date pages_data = [] days_data = [] for date in dates: image_file, text_content = get_image_and_text_for_date(date, image_directory, text_directory) days_data.append({ 'date': date, 'image_file': image_file, 'text_content': text_content }) # Check if we have collected data for 4 days, then start a new page if len(days_data) == 4: pages_data.append(days_data) days_data = [] # Add any remaining days to the last page if days_data: pages_data.append(days_data) return render_template('index.html', pages=pages_data) if __name__ == '__main__': app.run(debug=True)