|
| 1 | +""" |
| 2 | + This file upload the media generated in diffusion-nightly-test to a slack channel of SGLang |
| 3 | +""" |
| 4 | + |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import tempfile |
| 8 | +from datetime import datetime |
| 9 | +from urllib.parse import urlparse |
| 10 | +from urllib.request import urlopen |
| 11 | + |
| 12 | +logging.basicConfig(level=logging.INFO) |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | +import inspect |
| 16 | + |
| 17 | +try: |
| 18 | + import sglang.multimodal_gen.test.server.testcase_configs as configs |
| 19 | + from sglang.multimodal_gen.test.server.testcase_configs import DiffusionTestCase |
| 20 | + |
| 21 | + ALL_CASES = [] |
| 22 | + for name, value in inspect.getmembers(configs): |
| 23 | + if name.endswith("_CASES") or "_CASES_" in name: |
| 24 | + if ( |
| 25 | + isinstance(value, list) |
| 26 | + and len(value) > 0 |
| 27 | + and isinstance(value[0], DiffusionTestCase) |
| 28 | + ): |
| 29 | + ALL_CASES.extend(value) |
| 30 | + elif isinstance(value, list) and len(value) == 0: |
| 31 | + # Assume empty list with matching name is a valid case list container |
| 32 | + pass |
| 33 | + |
| 34 | + # Deduplicate cases by ID |
| 35 | + seen_ids = set() |
| 36 | + unique_cases = [] |
| 37 | + for c in ALL_CASES: |
| 38 | + if c.id not in seen_ids: |
| 39 | + seen_ids.add(c.id) |
| 40 | + unique_cases.append(c) |
| 41 | + ALL_CASES = unique_cases |
| 42 | + |
| 43 | +except Exception as e: |
| 44 | + logger.warning(f"Failed to import test cases: {e}") |
| 45 | + ALL_CASES = [] |
| 46 | + |
| 47 | + |
| 48 | +def _get_status_message(run_id, current_case_id, thread_messages=None): |
| 49 | + date_str = datetime.now().strftime("%d/%m") |
| 50 | + base_header = f"*🧵 for nightly test of {date_str}*\n*GitHub Run ID:* {run_id}\n*Total Tasks:* {len(ALL_CASES)}" |
| 51 | + |
| 52 | + if not ALL_CASES: |
| 53 | + return base_header |
| 54 | + |
| 55 | + default_emoji_for_case_in_progress = "⏳" |
| 56 | + status_map = {c.id: default_emoji_for_case_in_progress for c in ALL_CASES} |
| 57 | + |
| 58 | + if thread_messages: |
| 59 | + for msg in thread_messages: |
| 60 | + text = msg.get("text", "") |
| 61 | + # Look for case_id in the message (format: *Case ID:* `case_id`) |
| 62 | + for c in ALL_CASES: |
| 63 | + if f"*Case ID:* `{c.id}`" in text: |
| 64 | + status_map[c.id] = "✅" |
| 65 | + |
| 66 | + if current_case_id: |
| 67 | + status_map[current_case_id] = "✅" |
| 68 | + |
| 69 | + lines = [base_header, "", "*Tasks Status:*"] |
| 70 | + |
| 71 | + # Calculate padding |
| 72 | + max_len = max(len(c.id) for c in ALL_CASES) if ALL_CASES else 10 |
| 73 | + max_len = max(max_len, len("Case ID")) |
| 74 | + |
| 75 | + # Build markdown table inside a code block |
| 76 | + table_lines = ["```"] |
| 77 | + table_lines.append(f"| {'Case ID'.ljust(max_len)} | Status |") |
| 78 | + table_lines.append(f"| {'-' * max_len} | :----: |") |
| 79 | + |
| 80 | + for c in ALL_CASES: |
| 81 | + mark = status_map.get(c.id, default_emoji_for_case_in_progress) |
| 82 | + table_lines.append(f"| {c.id.ljust(max_len)} | {mark} |") |
| 83 | + |
| 84 | + table_lines.append("```") |
| 85 | + |
| 86 | + lines.extend(table_lines) |
| 87 | + |
| 88 | + return "\n".join(lines) |
| 89 | + |
| 90 | + |
| 91 | +def upload_file_to_slack( |
| 92 | + case_id: str = None, |
| 93 | + model: str = None, |
| 94 | + prompt: str = None, |
| 95 | + file_path: str = None, |
| 96 | + origin_file_path: str = None, |
| 97 | +) -> bool: |
| 98 | + temp_path = None |
| 99 | + try: |
| 100 | + from slack_sdk import WebClient |
| 101 | + |
| 102 | + run_id = os.getenv("GITHUB_RUN_ID", "local") |
| 103 | + |
| 104 | + token = os.environ.get("SGLANG_DIFFUSION_SLACK_TOKEN") |
| 105 | + if not token: |
| 106 | + logger.info(f"Slack upload failed: no token") |
| 107 | + return False |
| 108 | + |
| 109 | + if not file_path or not os.path.exists(file_path): |
| 110 | + logger.info(f"Slack upload failed: no file path") |
| 111 | + return False |
| 112 | + |
| 113 | + if origin_file_path and origin_file_path.startswith(("http", "https")): |
| 114 | + suffix = os.path.splitext(urlparse(origin_file_path).path)[1] or ".tmp" |
| 115 | + with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tf: |
| 116 | + with urlopen(origin_file_path) as response: |
| 117 | + tf.write(response.read()) |
| 118 | + temp_path = tf.name |
| 119 | + origin_file_path = temp_path |
| 120 | + |
| 121 | + uploads = [{"file": file_path, "title": "Generated Image"}] |
| 122 | + if origin_file_path and os.path.exists(origin_file_path): |
| 123 | + uploads.insert(0, {"file": origin_file_path, "title": "Original Image"}) |
| 124 | + |
| 125 | + message = ( |
| 126 | + f"*Case ID:* `{case_id}`\n" f"*Model:* `{model}`\n" f"*Prompt:* {prompt}" |
| 127 | + ) |
| 128 | + |
| 129 | + client = WebClient(token=token) |
| 130 | + channel_id = "C0A02NDF7UY" |
| 131 | + thread_ts = None |
| 132 | + |
| 133 | + parent_msg_text = None |
| 134 | + try: |
| 135 | + history = client.conversations_history(channel=channel_id, limit=100) |
| 136 | + for msg in history.get("messages", []): |
| 137 | + if f"*GitHub Run ID:* {run_id}" in msg.get("text", ""): |
| 138 | + # Use thread_ts if it exists (msg is a reply), otherwise use ts (msg is a parent) |
| 139 | + thread_ts = msg.get("thread_ts") or msg.get("ts") |
| 140 | + parent_msg_text = msg.get("text", "") |
| 141 | + logger.info(f"Found thread_ts: {thread_ts}") |
| 142 | + break |
| 143 | + except Exception as e: |
| 144 | + logger.warning(f"Failed to search slack history: {e}") |
| 145 | + |
| 146 | + if not thread_ts: |
| 147 | + try: |
| 148 | + text = _get_status_message(run_id, case_id) |
| 149 | + response = client.chat_postMessage(channel=channel_id, text=text) |
| 150 | + thread_ts = response["ts"] |
| 151 | + except Exception as e: |
| 152 | + logger.warning(f"Failed to create parent thread: {e}") |
| 153 | + |
| 154 | + # Upload first to ensure it's in history |
| 155 | + client.files_upload_v2( |
| 156 | + channel=channel_id, |
| 157 | + file_uploads=uploads, |
| 158 | + initial_comment=message, |
| 159 | + thread_ts=thread_ts, |
| 160 | + ) |
| 161 | + |
| 162 | + # Then update status based on thread replies |
| 163 | + if thread_ts: |
| 164 | + try: |
| 165 | + replies = client.conversations_replies( |
| 166 | + channel=channel_id, ts=thread_ts, limit=200 |
| 167 | + ) |
| 168 | + messages = replies.get("messages", []) |
| 169 | + new_text = _get_status_message(run_id, case_id, messages) |
| 170 | + |
| 171 | + # Only update if changed significantly (ignoring timestamp diffs if any) |
| 172 | + # But here we just check text content |
| 173 | + if new_text != parent_msg_text: |
| 174 | + client.chat_update(channel=channel_id, ts=thread_ts, text=new_text) |
| 175 | + except Exception as e: |
| 176 | + logger.warning(f"Failed to update parent message: {e}") |
| 177 | + |
| 178 | + logger.info(f"File uploaded successfully: {os.path.basename(file_path)}") |
| 179 | + return True |
| 180 | + |
| 181 | + except Exception as e: |
| 182 | + logger.info(f"Slack upload failed: {e}") |
| 183 | + return False |
| 184 | + finally: |
| 185 | + if temp_path and os.path.exists(temp_path): |
| 186 | + os.remove(temp_path) |
0 commit comments