Download src/engine/slack_formatter.py from YGCXLab/ux-research-agent-slackbot: direct link, hf CLI and curl.
- Browser
- Download file 6.06 kB
-
https://huggingface.co/spaces/YGCXLab/ux-research-agent-slackbot/resolve/main/src/engine/slack_formatter.py
- Command line
-
hf download hf://spaces/YGCXLab/ux-research-agent-slackbot/src/engine/slack_formatter.py
-
curl -L -o slack_formatter.py https://huggingface.co/spaces/YGCXLab/ux-research-agent-slackbot/resolve/main/src/engine/slack_formatter.py
6.06 kB
| """ | |
| Slack Block Kit formatting — separated from the search engine to keep | |
| the engine layer platform-agnostic. | |
| """ | |
| import logging | |
| import re | |
| from typing import Dict, List | |
| logger = logging.getLogger("SlackFormatter") | |
| # Slack enforces a maximum of 50 blocks per message. | |
| MAX_BLOCKS = 50 | |
| def markdown_to_slack(text: str) -> str: | |
| """Convert Markdown formatting to Slack mrkdwn. | |
| Handles: bold, italic, bullet lists, headers, links. | |
| """ | |
| # 1. Bullet lists first: * item or - item → • item (including indented) | |
| # (before bold/italic processing to avoid conflicts) | |
| text = re.sub(r'^(\s*)[\*\-]\s+', r'\1• ', text, flags=re.MULTILINE) | |
| # Use placeholders for bold to avoid italic regex re-matching | |
| _BOLD_OPEN = '\x00B' | |
| _BOLD_CLOSE = '\x00b' | |
| # 2. Headers (### Header → *Header*) | |
| text = re.sub(r'^#{1,6}\s+(.+)$', _BOLD_OPEN + r'\1' + _BOLD_CLOSE, text, flags=re.MULTILINE) | |
| # 3. Links [text](url) → <url|text> | |
| text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<\2|\1>', text) | |
| # 4. Bold+italic ***text*** → *_text_* (must come before bold/italic) | |
| text = re.sub(r'\*{3}(.+?)\*{3}', _BOLD_OPEN + r'\1' + _BOLD_CLOSE, text) | |
| # 5. Bold **text** → *text* | |
| text = re.sub(r'\*{2}(.+?)\*{2}', _BOLD_OPEN + r'\1' + _BOLD_CLOSE, text) | |
| # 6. Italic *text* → _text_ | |
| text = re.sub(r'(?<!\*)\*([^\s*](?:.*?[^\s*])?)\*(?!\*)', r'_\1_', text) | |
| # 7. Restore bold markers | |
| text = text.replace(_BOLD_OPEN, '*').replace(_BOLD_CLOSE, '*') | |
| # 8. Strikethrough ~~text~~ → ~text~ | |
| text = re.sub(r'~~(.+?)~~', r'~\1~', text) | |
| return text | |
| def _split_text(text: str, max_len: int = 3000) -> List[str]: | |
| """Split text into chunks of at most max_len, breaking at paragraph or line boundaries.""" | |
| if len(text) <= max_len: | |
| return [text] | |
| chunks = [] | |
| while text: | |
| if len(text) <= max_len: | |
| chunks.append(text) | |
| break | |
| # Try paragraph break first, then line break, then hard cut | |
| cut = text.rfind("\n\n", 0, max_len) | |
| if cut <= 0: | |
| cut = text.rfind("\n", 0, max_len) | |
| if cut <= 0: | |
| cut = max_len | |
| chunks.append(text[:cut].rstrip()) | |
| text = text[cut:].lstrip("\n") | |
| return chunks | |
| def convert_to_slack_blocks(data: Dict) -> List[Dict]: | |
| """Converts structured JSON response to Slack Block Kit blocks.""" | |
| blocks = [] | |
| SECTION_TEXT_LIMIT = 3000 | |
| # 1. Answer Section | |
| if "answer" in data and data["answer"]: | |
| answer_text = markdown_to_slack(data["answer"]) | |
| if len(answer_text) <= SECTION_TEXT_LIMIT: | |
| blocks.append({ | |
| "type": "section", | |
| "text": {"type": "mrkdwn", "text": answer_text} | |
| }) | |
| else: | |
| # Split long answer into multiple blocks at paragraph boundaries | |
| for chunk in _split_text(answer_text, SECTION_TEXT_LIMIT): | |
| blocks.append({ | |
| "type": "section", | |
| "text": {"type": "mrkdwn", "text": chunk} | |
| }) | |
| # 2. Sections (Sources) | |
| if "sections" in data: | |
| for section in data["sections"]: | |
| # Divider between sections | |
| blocks.append({"type": "divider"}) | |
| # Section Header | |
| section_name = section.get("name", "Section") | |
| blocks.append({ | |
| "type": "header", | |
| "text": { | |
| "type": "plain_text", | |
| "text": section_name, | |
| "emoji": True | |
| } | |
| }) | |
| # Items | |
| if "items" in section: | |
| for item in section["items"]: | |
| title = item.get("title", "No Title") | |
| date = item.get("date") | |
| summary = item.get("summary", "") | |
| link = item.get("link", {}) | |
| # Clean Title | |
| title = re.sub(r'\[.*?\]', '', title) # Remove [INTERNAL] etc | |
| title = re.sub(r'\(ID:.*?\)', '', title) # Remove (ID:...) | |
| title = title.strip() | |
| # Title Line with Link if available | |
| title_text = f"*{title}*" | |
| if date and date not in title: | |
| title_text += f" ({date})" | |
| text_content = f"{title_text}\n" | |
| if summary: | |
| text_content += f"• 요약: {summary}\n" | |
| if link and link.get("url"): | |
| link_text = link.get("text", "View") | |
| text_content += f"• 링크: <{link['url']}|{link_text}>" | |
| blocks.append({ | |
| "type": "section", | |
| "text": { | |
| "type": "mrkdwn", | |
| "text": text_content | |
| } | |
| }) | |
| # 3. Follow-up Questions | |
| follow_ups = data.get("follow_up_questions", []) | |
| if follow_ups: | |
| blocks.append({"type": "divider"}) | |
| numbered = "\n".join(f"{i+1}. {q}" for i, q in enumerate(follow_ups[:3])) | |
| blocks.append({ | |
| "type": "section", | |
| "text": {"type": "mrkdwn", "text": f"*💡 후속 질문*\n{numbered}"} | |
| }) | |
| # Fallback if empty | |
| if not blocks: | |
| blocks.append({ | |
| "type": "section", | |
| "text": { | |
| "type": "mrkdwn", | |
| "text": "No content generated." | |
| } | |
| }) | |
| # Enforce Slack's 50-block limit per message | |
| if len(blocks) > MAX_BLOCKS: | |
| logger.warning(f"Block count ({len(blocks)}) exceeds Slack limit ({MAX_BLOCKS}). Truncating.") | |
| blocks = blocks[:MAX_BLOCKS - 1] | |
| blocks.append({ | |
| "type": "section", | |
| "text": { | |
| "type": "mrkdwn", | |
| "text": "_... 결과가 너무 많아 일부만 표시했어요. 키워드를 좁혀서 다시 검색해 보세요._" | |
| } | |
| }) | |
| return blocks | |