├── requirements.txt ├── README.md ├── LICENSE └── digest.py /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp 2 | telethon 3 | pytz 4 | replicate 5 | requests 6 | logging 7 | argparse 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Telegram AI Digest Generator 3 | 4 | ![telegram-ai-digest-generator](https://github.com/user-attachments/assets/f35701c3-55de-4f5d-b287-8012b901a2eb) 5 | 6 | _Made by [t.me/aizvestia](https://t.me/aizvestia)_ 7 | 8 | Python script fetches Telegram channel messages, processes them into a digest via Claude AI, generates an image with Replicate API, and sends both to user's saved Telegram messages. 9 | 10 | ## Features 11 | 12 | - **Telegram API**: Fetches messages from a Telegram channel. 13 | - **Claude AI**: Generates a digest from the combined messages. 14 | - **Replicate API**: Generates an image based on the digest (FLUX + LoRa). 15 | - **Asyncio**: Utilizes asynchronous programming to handle API requests efficiently. 16 | 17 | ## Requirements 18 | 19 | The following Python libraries are required to run the script: 20 | 21 | - `aiohttp` 22 | - `telethon` 23 | - `pytz` 24 | - `replicate` 25 | - `requests` 26 | - `argparse` 27 | - `logging` 28 | 29 | You can install the required libraries by running: 30 | 31 | ```bash 32 | pip install -r requirements.txt 33 | ``` 34 | 35 | ## Setup 36 | 37 | 1. Clone the repository and navigate to the project directory. 38 | 39 | 2. Create a `.env` file in the root directory to store your environment variables. 40 | 41 | Example `.env` file: 42 | 43 | ``` 44 | API_ID= 45 | API_HASH= 46 | PHONE_NUMBER= 47 | CHANNEL_USERNAME= 48 | CLAUDE_API_KEY= 49 | REPLICATE_API_TOKEN= 50 | ``` 51 | 52 | 3. Install dependencies: 53 | 54 | ```bash 55 | pip install -r requirements.txt 56 | ``` 57 | 58 | ## Usage 59 | 60 | To run the script, use the following command: 61 | 62 | ```bash 63 | python digest.py 64 | ``` 65 | 66 | ### Date Range Arguments 67 | 68 | This script enables custom date ranges for digests via `start_date` and `end_date` arguments in `YYYY-MM-DD` format, defining the message fetch period. Without arguments, it defaults to the last 7 days, allowing for various timeframes like weekly reports or project milestones. 69 | 70 | Example usage with date range: 71 | 72 | ```bash 73 | python digest.py --start_date 2023-09-01 --end_date 2023-09-07 74 | ``` 75 | 76 | In this example, the script fetches messages from the specified Telegram channel between September 1-7, 2023. Without these arguments, it generates a digest for the last 7 days by default. 77 | 78 | The script will: 79 | 1. Load the environment variables from the `.env` file. 80 | 2. Fetch messages from the specified Telegram channel. 81 | 3. Process the messages into a digest using the Claude AI API. 82 | 4. Generate an image using the Replicate API. 83 | 5. Send the digest (with the generated image) to your saved messages on Telegram. 84 | 85 | ## Environment Variables 86 | 87 | The script requires the following environment variables to be set in a `.env` file: 88 | 89 | - `API_ID`: Your Telegram API ID. 90 | - `API_HASH`: Your Telegram API hash. 91 | - `PHONE_NUMBER`: Your phone number registered with Telegram. 92 | - `CHANNEL_USERNAME`: The username of the Telegram channel to fetch messages from. 93 | - `CLAUDE_API_KEY`: API key for Claude AI to generate text digest. 94 | - `REPLICATE_API_TOKEN`: API token for Replicate API to generate images. 95 | 96 | ## How to Obtain API Tokens 97 | 98 | ### Telegram API Credentials 99 | 100 | 1. Go to [Telegram's my.telegram.org](https://my.telegram.org/) and log in with your Telegram account. 101 | 2. Navigate to the "API development tools" section. 102 | 3. Create a new application and you will receive your `API_ID` and `API_HASH`. 103 | 4. Use your Telegram-registered phone number for the `PHONE_NUMBER` value. 104 | 5. Find the username of the Telegram channel you wish to fetch messages from and add it to `CHANNEL_USERNAME`. 105 | 106 | ### Claude AI API Key 107 | 108 | 1. Register or sign in to Claude AI (from Anthropic) via their developer console. 109 | 2. Go to the API section and generate your API key. 110 | 3. Use this key as `CLAUDE_API_KEY` in your `.env` file. 111 | 112 | ### Replicate API Token 113 | 114 | 1. Sign up or log in at [Replicate](https://replicate.com/). 115 | 2. Navigate to the account settings and find your API token. 116 | 3. Use the API token as `REPLICATE_API_TOKEN` in your `.env` file. 117 | 118 | ## Logging 119 | 120 | The script uses the built-in `logging` library to provide detailed logs about the execution. Logs are displayed in the console, including warnings and errors related to missing environment variables or failed API requests. 121 | 122 | ## License 123 | 124 | This project is licensed under the MIT License. See the `LICENSE` file for details. 125 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /digest.py: -------------------------------------------------------------------------------- 1 | import os 2 | import asyncio 3 | import aiohttp 4 | import logging 5 | from datetime import datetime, timedelta 6 | from pathlib import Path 7 | from telethon import TelegramClient 8 | from pytz import UTC 9 | import replicate 10 | import requests 11 | from io import BytesIO 12 | import re 13 | import subprocess 14 | import argparse 15 | from datetime import datetime 16 | import random 17 | 18 | # Set up logging 19 | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') 20 | 21 | def load_env_from_file(env_file='.env'): 22 | env_path = Path(env_file) 23 | if env_path.exists(): 24 | with env_path.open() as f: 25 | for line in f: 26 | line = line.strip() 27 | if line and not line.startswith('#'): 28 | key, value = line.split('=', 1) 29 | os.environ[key.strip()] = value.strip() 30 | else: 31 | logging.warning(f".env file not found at {env_path.absolute()}. Using system environment variables.") 32 | 33 | load_env_from_file() 34 | 35 | def get_env_variable(var_name): 36 | value = os.getenv(var_name) 37 | if value is None: 38 | raise ValueError(f"Environment variable '{var_name}' is not set.") 39 | return value 40 | 41 | # Telegram API credentials 42 | try: 43 | API_ID = int(get_env_variable('API_ID')) 44 | API_HASH = get_env_variable('API_HASH') 45 | PHONE_NUMBER = get_env_variable('PHONE_NUMBER') 46 | CHANNEL_USERNAME = get_env_variable('CHANNEL_USERNAME') 47 | CLAUDE_API_KEY = get_env_variable('CLAUDE_API_KEY') 48 | REPLICATE_API_TOKEN = get_env_variable('REPLICATE_API_TOKEN') 49 | except ValueError as e: 50 | logging.error(f"Environment variable error: {str(e)}") 51 | raise 52 | 53 | os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN 54 | logging.info(f"Replicate API token: {REPLICATE_API_TOKEN[:5]}...{REPLICATE_API_TOKEN[-5:]}") 55 | 56 | CLAUDE_API_URL = "https://api.anthropic.com/v1/messages" 57 | 58 | logging.debug(f"API_ID is set: {'Yes' if API_ID else 'No'}") 59 | logging.debug(f"API_HASH is set: {'Yes' if API_HASH else 'No'}") 60 | logging.debug(f"PHONE_NUMBER is set: {'Yes' if PHONE_NUMBER else 'No'}") 61 | logging.debug(f"CHANNEL_USERNAME: {CHANNEL_USERNAME}") 62 | 63 | required_vars = ['API_ID', 'API_HASH', 'PHONE_NUMBER', 'CHANNEL_USERNAME', 'CLAUDE_API_KEY', 'REPLICATE_API_TOKEN'] 64 | missing_vars = [var for var in required_vars if not globals().get(var)] 65 | 66 | if missing_vars: 67 | raise ValueError(f"The following required environment variables are not set: {', '.join(missing_vars)}") 68 | 69 | MAX_REQUESTS_PER_MINUTE = 30 70 | REQUEST_INTERVAL = 60 / MAX_REQUESTS_PER_MINUTE 71 | 72 | semaphore = asyncio.Semaphore(MAX_REQUESTS_PER_MINUTE) 73 | 74 | client = TelegramClient('session', API_ID, API_HASH) 75 | 76 | async def call_claude_api(session, prompt, retry=True): 77 | headers = { 78 | "Content-Type": "application/json", 79 | "x-api-key": CLAUDE_API_KEY, 80 | "anthropic-version": "2023-06-01" 81 | } 82 | 83 | payload = { 84 | "model": "claude-3-5-sonnet-20240620", 85 | "max_tokens": 4092, 86 | "messages": [{"role": "user", "content": prompt}] 87 | } 88 | 89 | async with semaphore: 90 | try: 91 | logging.debug(f"Calling Claude API with prompt length: {len(prompt)}") 92 | async with session.post(CLAUDE_API_URL, json=payload, headers=headers) as response: 93 | if response.status == 200: 94 | result = await response.json() 95 | logging.debug("Claude API call successful") 96 | return result['content'][0]['text'] 97 | else: 98 | error_text = await response.text() 99 | logging.error(f"API call failed with status {response.status}: {error_text}") 100 | if retry: 101 | logging.info("Retrying API call...") 102 | await asyncio.sleep(REQUEST_INTERVAL) 103 | return await call_claude_api(session, prompt, retry=False) 104 | return None 105 | except Exception as e: 106 | logging.error(f"Error in API call: {str(e)}") 107 | if retry: 108 | logging.info("Retrying API call...") 109 | await asyncio.sleep(REQUEST_INTERVAL) 110 | return await call_claude_api(session, prompt, retry=False) 111 | return None 112 | finally: 113 | await asyncio.sleep(REQUEST_INTERVAL) 114 | 115 | def format_date_range(start_date, end_date): 116 | months_ru = [ 117 | 'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 118 | 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря' 119 | ] 120 | 121 | if start_date.month == end_date.month and start_date.year == end_date.year: 122 | return f"{start_date.day}-{end_date.day} {months_ru[end_date.month - 1]}" 123 | else: 124 | return f"{start_date.day} {months_ru[start_date.month - 1]} - {end_date.day} {months_ru[end_date.month - 1]}" 125 | 126 | async def create_digest(messages, start_date, end_date): 127 | if not messages: 128 | logging.error("No messages to create digest from") 129 | return "No messages were found to create a digest." 130 | 131 | date_range = format_date_range(start_date, end_date) 132 | logging.debug(f"Formatted date range: {date_range}") 133 | 134 | async with aiohttp.ClientSession() as session: 135 | prompt = f"""Create a digest for Telegram messages from {date_range}. Summarize key points, include original post links, apply links to the key word in the original post. DO NOT use "learn more" or "подробнее". Use Russian language. 136 | Format: 137 | - Title: "Дайджест ИИзвестий за неделю {date_range}" 138 | - Jump to content, no intro, no outro, no "Here's the digest in the requested format:" kind of text. 139 | - Brief intro (2-3 sentences) 140 | - Sections with emojis (e.g., LLM, Генеративные модели, Подборки курсов, Всякая-всячина) 141 | - Use dash (-) for news items, NO extra line breaks between items: 142 | ``` 143 | EMOJI Title 144 | - News1 145 | - News2 146 | - News3 147 | ``` 148 | - Include key aspects and brief comments (2-3 sentences max) 149 | - Link keywords to original posts 150 | - End with: "#ИИзвестия\n\n@aizvestia" 151 | 152 | Use Telegram Markdown: 153 | **bold**, _italic_, __underline__, ~strikethrough~, ||spoiler||, [inline URL](http://www.example.com/), `code`, ```block code``` 154 | 155 | Messages to summarize: 156 | "{messages}" 157 | 158 | Output pure markdown, be concise, MUST start with content, no intro. Avoid extra line breaks between list items. Use bold for section titles instead of #.""" 159 | digest_markdown = await call_claude_api(session, prompt) 160 | return digest_markdown 161 | 162 | def get_previous_week_range(): 163 | today = datetime.now(UTC) 164 | if today.weekday() == 6: # If today is Sunday 165 | most_recent_monday = today - timedelta(days=6) 166 | end_date = today 167 | else: 168 | most_recent_monday = today - timedelta(days=today.weekday() + 1) 169 | end_date = most_recent_monday + timedelta(days=6) 170 | 171 | start_date = most_recent_monday.replace(hour=0, minute=0, second=0, microsecond=0) 172 | end_date = end_date.replace(hour=23, minute=59, second=59, microsecond=999999) 173 | return start_date, end_date 174 | 175 | async def generate_image_prompt(digest): 176 | async with aiohttp.ClientSession() as session: 177 | prompt = f"""Create a minimalist image prompt for FLUX 1 PRO that: 178 | - Uses simple telegraphic English with comma-separated elements 179 | - Describes a clean retrofuturistic poster design 180 | - ABSOLUTELY NO TEXT OR TEXT-LIKE ELEMENTS of any kind 181 | - Keeps under 300 characters total 182 | - Selects 3-5 key visual concepts from the digest (not all) 183 | - Uses abstract visual metaphors instead of literal representations 184 | - Emphasizes white space and clean composition 185 | - Incorporates collage and papercut aesthetic 186 | - Focuses on retrofuturism and techno-optimism 187 | 188 | AI news digest: 189 | === 190 | {digest} 191 | === 192 | 193 | Important: 194 | - NO text, NO UI elements, NO logos, NO numbers, NO labels whatsoever 195 | - Favor abstract symbols over detailed illustrations 196 | - Emphasize composition and negative space 197 | - Be weird and creative but SIMPLE 198 | 199 | Output only the final image prompt.""" 200 | 201 | image_prompt = await call_claude_api(session, prompt) 202 | return image_prompt.strip() 203 | 204 | # Add these styles after the existing constants 205 | REDPANDA_STYLES = [ 206 | "any", 207 | "realistic_image", 208 | "digital_illustration", 209 | "digital_illustration/pixel_art", 210 | "digital_illustration/hand_drawn", 211 | "digital_illustration/grain", 212 | "digital_illustration/infantile_sketch", 213 | "digital_illustration/2d_art_poster", 214 | "digital_illustration/handmade_3d", 215 | "digital_illustration/hand_drawn_outline", 216 | "digital_illustration/engraving_color", 217 | "digital_illustration/2d_art_poster_2", 218 | "realistic_image/b_and_w", 219 | "realistic_image/hard_flash", 220 | "realistic_image/hdr", 221 | "realistic_image/natural_light", 222 | "realistic_image/studio_portrait", 223 | "realistic_image/enterprise", 224 | "realistic_image/motion_blur" 225 | ] 226 | 227 | def generate_and_save_image(prompt, model="flux"): 228 | try: 229 | logging.info(f"Generating image with {model} model. Prompt: {prompt}") 230 | 231 | if model == "flux": 232 | output = replicate.run( 233 | "black-forest-labs/flux-1.1-pro-ultra", 234 | input={ 235 | "prompt": prompt, 236 | "output_format": "jpg", 237 | "output_quality": 80, 238 | "safety_tolerance": 2, 239 | "aspect_ratio": "4:5" 240 | } 241 | ) 242 | else: # redpanda 243 | output = replicate.run( 244 | "recraft-ai/recraft-v3", 245 | input={ 246 | "size": "1024x1707", # Close to 4:5 ratio 247 | "style": random.choice(REDPANDA_STYLES), 248 | "prompt": prompt 249 | } 250 | ) 251 | 252 | logging.info(f"Replicate output: {output}") 253 | 254 | if isinstance(output, list) and len(output) > 0: 255 | image_url = output[0] 256 | elif isinstance(output, str): 257 | image_url = output 258 | else: 259 | logging.error(f"Unexpected output format from Replicate: {output}") 260 | return None 261 | 262 | # Download the image 263 | response = requests.get(image_url) 264 | response.raise_for_status() 265 | 266 | # Save the original webp image 267 | with open("digest_illustration_original.webp", "wb") as f: 268 | f.write(response.content) 269 | 270 | # Convert webp to png using ImageMagick 271 | try: 272 | subprocess.run(["convert", "digest_illustration_original.webp", "digest_illustration.png"], check=True) 273 | logging.info("Image converted successfully") 274 | return "digest_illustration.png" 275 | except subprocess.CalledProcessError as e: 276 | logging.error(f"Error converting image: {e}") 277 | return "digest_illustration_original.webp" # Return the original webp if conversion fails 278 | 279 | except replicate.exceptions.ReplicateError as e: 280 | logging.error(f"Replicate API error: {str(e)}") 281 | except requests.exceptions.RequestException as e: 282 | logging.error(f"Error downloading image: {str(e)}") 283 | except Exception as e: 284 | logging.error(f"Error in generate_and_save_image: {str(e)}") 285 | return None 286 | 287 | def remove_extra_line_breaks(text): 288 | # Remove extra line breaks between list items 289 | text = re.sub(r'(\n- .+?)\n+(?=\n-)', r'\1', text, flags=re.DOTALL) 290 | 291 | # Remove extra line breaks between sections 292 | text = re.sub(r'\n{3,}', '\n\n', text) 293 | 294 | return text 295 | 296 | async def main(): 297 | parser = argparse.ArgumentParser(description='Generate digest for a specific date range.') 298 | parser.add_argument('--startdate', type=str, required=True, help='Start date in YYYY-MM-DD format') 299 | parser.add_argument('--enddate', type=str, required=True, help='End date in YYYY-MM-DD format') 300 | parser.add_argument('--model', type=str, choices=['flux', 'redpanda'], default='flux', 301 | help='Choose image generation model (default: flux)') 302 | args = parser.parse_args() 303 | 304 | start_date = datetime.strptime(args.startdate, '%Y-%m-%d').replace(tzinfo=UTC) 305 | end_date = datetime.strptime(args.enddate, '%Y-%m-%d').replace(hour=23, minute=59, second=59, microsecond=999999, tzinfo=UTC) 306 | 307 | logging.info(f"Using phone number: {PHONE_NUMBER}") 308 | await client.start(phone=PHONE_NUMBER) 309 | logging.info("Connected to Telegram") 310 | 311 | channel = await client.get_entity(CHANNEL_USERNAME) 312 | logging.info(f"Retrieved channel entity: {channel.title}") 313 | 314 | logging.info(f"Fetching messages from {start_date.strftime('%Y-%m-%d %H:%M:%S')} to {end_date.strftime('%Y-%m-%d %H:%M:%S')}") 315 | 316 | messages = [] 317 | message_count = 0 318 | async for message in client.iter_messages(channel, offset_date=end_date, limit=None): 319 | if message.date < start_date: 320 | break 321 | if start_date <= message.date <= end_date: 322 | message_link = None 323 | if message.text: 324 | message_link = f"https://t.me/{channel.username}/{message.id}" 325 | messages.append(f"{message.date.strftime('%Y-%m-%d %H:%M')} - {message.text}\nMessage link: {message_link}") 326 | message_count += 1 327 | logging.debug(f"Fetched message: Date={message.date}, Has text: True, Message link: {message_link}") 328 | else: 329 | logging.debug(f"Skipped message: Date={message.date}, Has text: False") 330 | 331 | messages.reverse() 332 | logging.info(f"Total messages fetched: {message_count}") 333 | 334 | if not messages: 335 | logging.error("No messages were fetched from the channel for the specified week") 336 | return 337 | 338 | combined_messages = "\n\n".join(messages) 339 | logging.debug(f"Combined messages length: {len(combined_messages)}") 340 | 341 | logging.info("Creating digest using Claude AI...") 342 | logging.debug(f"Start date: {start_date}, End date: {end_date}") 343 | digest_markdown = await create_digest(combined_messages, start_date, end_date) 344 | 345 | if digest_markdown: 346 | # Apply post-processing to remove extra line breaks 347 | digest_markdown = remove_extra_line_breaks(digest_markdown) 348 | 349 | logging.debug(f"Processed digest start: {digest_markdown[:500]}") 350 | 351 | image_prompt = await generate_image_prompt(digest_markdown) 352 | logging.info(f"Generated image prompt: {image_prompt}") 353 | 354 | logging.info(f"Using Replicate API token: {REPLICATE_API_TOKEN[:5]}...{REPLICATE_API_TOKEN[-5:]}") 355 | 356 | image_path = generate_and_save_image(image_prompt, model=args.model) 357 | 358 | if image_path: 359 | logging.info(f"Generated image saved at: {image_path}") 360 | 361 | try: 362 | # Send the image with the digest text as caption 363 | await client.send_file('me', image_path, caption=digest_markdown, parse_mode='md') 364 | logging.info("Digest image with text caption sent to Saved Messages") 365 | except Exception as e: 366 | logging.error(f"Error sending image with caption: {str(e)}") 367 | logging.warning("Sending digest as text only.") 368 | await client.send_message('me', digest_markdown, parse_mode='md') 369 | logging.info("Digest sent to Saved Messages as text only") 370 | else: 371 | logging.error("Failed to generate or save image") 372 | logging.warning("Sending digest as text only.") 373 | await client.send_message('me', digest_markdown, parse_mode='md') 374 | logging.info("Digest sent to Saved Messages as text only") 375 | 376 | else: 377 | logging.error("Failed to create digest") 378 | 379 | await client.disconnect() 380 | 381 | if __name__ == "__main__": 382 | with client: 383 | client.loop.run_until_complete(main()) 384 | --------------------------------------------------------------------------------