Spaces:
Sleeping
Sleeping
File size: 15,938 Bytes
5efb046 1eab7aa 74952b9 1eab7aa 74952b9 5efb046 d075410 5efb046 1eab7aa 5efb046 1eab7aa 5efb046 1eab7aa 5efb046 1eab7aa 5efb046 1eab7aa 5efb046 1eab7aa 74952b9 1eab7aa 5efb046 1eab7aa 5efb046 1eab7aa 5efb046 1eab7aa 74952b9 1eab7aa 5efb046 d075410 5efb046 d075410 5efb046 d075410 5efb046 d075410 5efb046 d075410 1eab7aa 5efb046 74952b9 1eab7aa 74952b9 5efb046 1eab7aa 74952b9 1eab7aa 5efb046 1eab7aa 74952b9 1eab7aa 74952b9 1eab7aa 74952b9 1eab7aa 5efb046 1eab7aa 74952b9 1eab7aa 74952b9 1eab7aa 74952b9 1eab7aa 74952b9 1eab7aa 74952b9 5efb046 1eab7aa 74952b9 1eab7aa 74952b9 1eab7aa 74952b9 1eab7aa 74952b9 1eab7aa 5efb046 1eab7aa 5efb046 1eab7aa 5efb046 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 |
# app.py - Simplified version that definitely works on HF Spaces
import os
import re
import json
from datetime import datetime
from typing import List, Dict, Any
import gradio as gr
import requests
import asyncio
from threading import Thread
# Configuration
WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET")
HF_TOKEN = os.getenv("HF_TOKEN")
# Storage for operations
tag_operations_store: List[Dict[str, Any]] = []
# Recognized tags
RECOGNIZED_TAGS = {
"pytorch", "tensorflow", "jax", "transformers", "diffusers",
"text-generation", "text-classification", "question-answering",
"text-to-image", "image-classification", "object-detection",
"fill-mask", "token-classification", "translation", "summarization",
"feature-extraction", "sentence-similarity", "zero-shot-classification",
"image-to-text", "automatic-speech-recognition", "audio-classification",
"voice-activity-detection", "depth-estimation", "image-segmentation",
"video-classification", "reinforcement-learning", "tabular-classification",
"tabular-regression", "time-series-forecasting", "graph-ml", "robotics",
"computer-vision", "nlp", "cv", "multimodal", "gguf", "safetensors",
"llamacpp", "onnx", "mlx", "machine-learning", "deep-learning"
}
def extract_tags_from_text(text: str) -> List[str]:
"""Extract potential tags from discussion text"""
text_lower = text.lower()
explicit_tags = []
# Pattern 1: "tag: something" or "tags: something"
tag_pattern = r"tags?:\s*([a-zA-Z0-9-_,\s]+)"
matches = re.findall(tag_pattern, text_lower)
for match in matches:
tags = [tag.strip() for tag in match.split(",")]
explicit_tags.extend(tags)
# Pattern 2: "#hashtag" style
hashtag_pattern = r"#([a-zA-Z0-9-_]+)"
hashtag_matches = re.findall(hashtag_pattern, text_lower)
explicit_tags.extend(hashtag_matches)
# Pattern 3: Look for recognized tags mentioned in natural text
mentioned_tags = []
for tag in RECOGNIZED_TAGS:
if tag in text_lower:
mentioned_tags.append(tag)
# Combine and deduplicate
all_tags = list(set(explicit_tags + mentioned_tags))
# Filter to only include recognized tags or explicitly mentioned ones
valid_tags = []
for tag in all_tags:
if tag in RECOGNIZED_TAGS or tag in explicit_tags:
valid_tags.append(tag)
return valid_tags
def process_tags_sync(all_tags: List[str], repo_name: str) -> List[str]:
"""Process tags using direct HuggingFace Hub API calls (synchronous)"""
print(f"π§ Processing tags: {all_tags} for repo: {repo_name}")
result_messages = []
if not HF_TOKEN:
error_msg = "No HF_TOKEN configured"
print(f"β {error_msg}")
return [error_msg]
try:
from huggingface_hub import HfApi, model_info, dataset_info, space_info, ModelCard, ModelCardData
from huggingface_hub.utils import HfHubHTTPError
from huggingface_hub import CommitOperationAdd
hf_api = HfApi(token=HF_TOKEN)
# Determine repository type
repo_type = None
repo_info = None
for repo_type_to_try in ["model", "dataset", "space"]:
try:
print(f"π Trying to access {repo_name} as {repo_type_to_try}...")
if repo_type_to_try == "model":
repo_info = model_info(repo_id=repo_name, token=HF_TOKEN)
elif repo_type_to_try == "dataset":
repo_info = dataset_info(repo_id=repo_name, token=HF_TOKEN)
elif repo_type_to_try == "space":
repo_info = space_info(repo_id=repo_name, token=HF_TOKEN)
repo_type = repo_type_to_try
print(f"β
Found repository as {repo_type}")
break
except HfHubHTTPError as e:
if "404" in str(e):
continue
else:
print(f"β Error accessing as {repo_type_to_try}: {e}")
continue
except Exception as e:
print(f"β Unexpected error for {repo_type_to_try}: {e}")
continue
if not repo_type or not repo_info:
error_msg = f"Repository '{repo_name}' not found"
return [f"Error: {error_msg}"]
current_tags = repo_info.tags if repo_info.tags else []
print(f"π·οΈ Current tags: {current_tags}")
# Process each tag
for tag in all_tags:
try:
if tag in current_tags:
msg = f"Tag '{tag}': Already exists"
result_messages.append(msg)
continue
# Add the new tag
updated_tags = current_tags + [tag]
# Create/update model card
try:
card = ModelCard.load(repo_name, token=HF_TOKEN, repo_type=repo_type)
if not hasattr(card, "data") or card.data is None:
card.data = ModelCardData()
except HfHubHTTPError:
card = ModelCard("")
card.data = ModelCardData()
# Update tags
card_dict = card.data.to_dict()
card_dict["tags"] = updated_tags
card.data = ModelCardData(**card_dict)
pr_title = f"Add '{tag}' tag"
pr_description = f"""
## Add tag: {tag}
This PR adds the `{tag}` tag to the {repo_type} repository.
**Changes:**
- Added `{tag}` to {repo_type} tags
- Updated from {len(current_tags)} to {len(updated_tags)} tags
**Current tags:** {", ".join(current_tags) if current_tags else "None"}
**New tags:** {", ".join(updated_tags)}
*This PR was created automatically by the HF Tagging Bot.*
"""
commit_info = hf_api.create_commit(
repo_id=repo_name,
repo_type=repo_type,
operations=[
CommitOperationAdd(
path_in_repo="README.md",
path_or_fileobj=str(card).encode("utf-8")
)
],
commit_message=pr_title,
commit_description=pr_description,
token=HF_TOKEN,
create_pr=True,
)
pr_url = getattr(commit_info, 'pr_url', str(commit_info))
msg = f"Tag '{tag}': [PR created]({pr_url})"
result_messages.append(msg)
except Exception as tag_error:
error_msg = f"Tag '{tag}': Error - {str(tag_error)}"
result_messages.append(error_msg)
return result_messages
except Exception as e:
error_msg = f"Processing failed: {str(e)}"
return [error_msg]
def process_webhook_comment(webhook_data: Dict[str, Any]):
"""Process webhook to detect and add tags"""
try:
comment_content = webhook_data["comment"]["content"]
discussion_title = webhook_data["discussion"]["title"]
repo_name = webhook_data["repo"]["name"]
discussion_num = webhook_data["discussion"]["num"]
comment_author = webhook_data["comment"]["author"].get("id", "unknown")
print(f"π Processing comment from {comment_author} on {repo_name}")
print(f"π Comment: {comment_content}")
# Extract tags
comment_tags = extract_tags_from_text(comment_content)
title_tags = extract_tags_from_text(discussion_title)
all_tags = list(set(comment_tags + title_tags))
if not all_tags:
print("β No tags found")
return "No recognizable tags found"
print(f"π·οΈ Found tags: {all_tags}")
result_messages = process_tags_sync(all_tags, repo_name)
# Store interaction
interaction = {
"timestamp": datetime.now().isoformat(),
"repo": repo_name,
"discussion_title": discussion_title,
"discussion_num": discussion_num,
"comment_author": comment_author,
"detected_tags": all_tags,
"results": result_messages,
}
tag_operations_store.append(interaction)
# Keep only last 100 operations
if len(tag_operations_store) > 100:
tag_operations_store.pop(0)
return " | ".join(result_messages)
except Exception as e:
error_msg = f"Error processing webhook: {str(e)}"
print(f"β {error_msg}")
return error_msg
def handle_webhook_request(request: gr.Request):
"""Handle webhook via Gradio's request handling"""
try:
print(f"π₯ Received request: {request.method}")
if request.method != "POST":
return {"error": "Method not allowed"}
# Get request data
if hasattr(request, 'json') and callable(request.json):
payload = request.json()
else:
# Fallback for different request formats
return {"error": "Could not parse JSON"}
print(f"π₯ Webhook payload: {payload.get('event', {})}")
# Verify webhook secret if configured
if WEBHOOK_SECRET:
webhook_secret = request.headers.get("X-Webhook-Secret")
if webhook_secret != WEBHOOK_SECRET:
print("β Invalid webhook secret")
return {"error": "Invalid webhook secret"}
event = payload.get("event", {})
scope = event.get("scope")
action = event.get("action")
# Only process discussion comment creation (not PRs)
if (scope in ["discussion", "discussion.comment"] and
action == "create" and
not payload.get("discussion", {}).get("isPullRequest", False)):
# Process webhook in a separate thread
def process_in_background():
process_webhook_comment(payload)
thread = Thread(target=process_in_background)
thread.start()
return {"status": "processing"}
return {"status": "ignored"}
except Exception as e:
print(f"β Webhook error: {e}")
return {"error": str(e)}
def create_gradio_interface():
"""Create Gradio interface"""
with gr.Blocks(title="HF Tagging Bot", theme=gr.themes.Soft()) as interface:
gr.Markdown("# π·οΈ HuggingFace Tagging Bot")
gr.Markdown("*Automatically adds tags to repositories when mentioned in discussions*")
with gr.Tab("π Status"):
status_text = gr.HTML(f"""
<h2>Bot Configuration</h2>
<ul>
<li>π <strong>HF Token</strong>: {'β
Configured' if HF_TOKEN else 'β Missing'}</li>
<li>π <strong>Webhook Secret</strong>: {'β
Configured' if WEBHOOK_SECRET else 'β Missing'}</li>
<li>π <strong>Operations Processed</strong>: {len(tag_operations_store)}</li>
</ul>
<h2>Webhook Endpoint</h2>
<p><code>https://asmaa105-hf-tagging-bot.hf.space/webhook</code></p>
<h2>Setup Instructions</h2>
<ol>
<li>Go to your repository Settings β Webhooks</li>
<li>Add webhook URL above</li>
<li>Select "Discussion comments" events</li>
<li>Add your webhook secret if configured</li>
</ol>
""")
with gr.Tab("π Operations Log"):
def get_recent_operations():
if not tag_operations_store:
return "No operations yet. The webhook is ready to receive requests."
recent = tag_operations_store[-10:]
output = []
for op in reversed(recent):
output.append(f"""
**{op['repo']}** - {op['timestamp'][:19]}
- π€ Author: {op['comment_author']}
- π·οΈ Tags: {', '.join(op['detected_tags']) if op['detected_tags'] else 'None'}
- π Results: {' | '.join(op['results'][:2])}{'...' if len(op['results']) > 2 else ''}
---""")
return "\n".join(output)
operations_display = gr.Textbox(
label="Recent Operations",
value=get_recent_operations(),
lines=15,
interactive=False
)
refresh_btn = gr.Button("π Refresh Log")
refresh_btn.click(fn=get_recent_operations, outputs=operations_display)
with gr.Tab("π§ͺ Test Webhook"):
gr.Markdown("### Test Webhook Processing")
test_repo = gr.Textbox(label="Repository", value="asmaa105/streamlitweb1")
test_comment = gr.Textbox(label="Test Comment", value="Please add tags: pytorch, transformers", lines=3)
test_btn = gr.Button("π§ Test Processing")
test_result = gr.Textbox(label="Result", lines=5, interactive=False)
def test_webhook_processing(repo, comment):
try:
# Create mock webhook data
mock_webhook = {
"event": {"action": "create", "scope": "discussion"},
"comment": {"content": comment, "author": {"id": "test-user"}},
"discussion": {"title": "Test", "num": 1, "isPullRequest": False},
"repo": {"name": repo}
}
result = process_webhook_comment(mock_webhook)
return f"β
Test completed!\n\nResult: {result}"
except Exception as e:
return f"β Test failed: {str(e)}"
test_btn.click(fn=test_webhook_processing, inputs=[test_repo, test_comment], outputs=test_result)
with gr.Tab("π·οΈ Supported Tags"):
gr.Markdown(f"""
## Supported Tags ({len(RECOGNIZED_TAGS)} total)
{', '.join(sorted(RECOGNIZED_TAGS))}
## Tag Detection Examples
- **Explicit**: `tag: pytorch` or `tags: pytorch, transformers`
- **Hashtag**: `#pytorch #transformers`
- **Natural**: "This model uses pytorch and transformers"
""")
gr.Markdown("### Test Tag Detection")
test_input = gr.Textbox(
label="Test Comment",
placeholder="Enter a comment to test tag detection...",
lines=3,
value="Please add tags: pytorch, transformers"
)
test_output = gr.Textbox(
label="Detected Tags",
lines=2,
interactive=False
)
test_btn = gr.Button("π Test Detection")
def test_tag_detection(text):
if not text:
return "Enter some text to test"
tags = extract_tags_from_text(text)
if tags:
return f"Found {len(tags)} tags: {', '.join(tags)}"
else:
return "No tags detected in this text"
test_btn.click(fn=test_tag_detection, inputs=test_input, outputs=test_output)
return interface
# Create the Gradio interface
demo = create_gradio_interface()
# Add webhook handling via Gradio's API
if hasattr(demo, 'add_api_route'):
demo.add_api_route("/webhook", handle_webhook_request, methods=["POST"])
if __name__ == "__main__":
print("π HF Tagging Bot - Simplified version starting")
print(f"π HF_TOKEN: {'β
Configured' if HF_TOKEN else 'β Missing'}")
print(f"π Webhook Secret: {'β
Configured' if WEBHOOK_SECRET else 'β Missing'}")
print("π Webhook endpoint: /webhook")
demo.launch(server_name="0.0.0.0", server_port=7860) |