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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
| 3 |
+
import logging
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from fastapi import FastAPI, Request, Response
|
| 7 |
+
import uvicorn
|
| 8 |
+
from pyrogram import Client, filters
|
| 9 |
+
from pyrogram.types import (
|
| 10 |
+
InlineKeyboardMarkup,
|
| 11 |
+
InlineKeyboardButton,
|
| 12 |
+
CallbackQuery,
|
| 13 |
+
Message,
|
| 14 |
+
Update,
|
| 15 |
+
)
|
| 16 |
+
from pyrogram.errors import BadRequest
|
| 17 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 18 |
+
|
| 19 |
+
# ---------- CONFIG ----------
|
| 20 |
+
TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
|
| 21 |
+
HF_TOKEN = os.environ["HF_TOKEN"]
|
| 22 |
+
DATASET_REPO = "your-username/my-telegram-files" # <-- CHANGE THIS
|
| 23 |
+
WEBHOOK_URL = os.environ.get("WEBHOOK_URL_BASE", "https://your-space.hf.space")
|
| 24 |
+
WEBHOOK_PATH = f"/{TOKEN}"
|
| 25 |
+
|
| 26 |
+
TEMP_DIR = Path("/tmp/telegram_bot_files")
|
| 27 |
+
TEMP_DIR.mkdir(exist_ok=True)
|
| 28 |
+
|
| 29 |
+
hf_api = HfApi(token=HF_TOKEN)
|
| 30 |
+
|
| 31 |
+
# ---------- LOGGING ----------
|
| 32 |
+
logging.basicConfig(level=logging.INFO)
|
| 33 |
+
logger = logging.getLogger(__name__)
|
| 34 |
+
|
| 35 |
+
# ---------- PYROGRAM CLIENT ----------
|
| 36 |
+
app = Client(
|
| 37 |
+
name="my_bot",
|
| 38 |
+
bot_token=TOKEN,
|
| 39 |
+
api_id=12345, # dummy values – webhook only needs token
|
| 40 |
+
api_hash="abc123",
|
| 41 |
+
workdir="/tmp",
|
| 42 |
+
sleep_threshold=0, # disable flood wait sleep in a serverless env
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# ---------- FASTAPI ----------
|
| 46 |
+
fastapi_app = FastAPI()
|
| 47 |
+
|
| 48 |
+
@app.on_message(filters.command("start"))
|
| 49 |
+
async def start_command(client: Client, message: Message):
|
| 50 |
+
await message.reply_text(
|
| 51 |
+
"Send me any file and I'll store it in your personal dataset folder.\n"
|
| 52 |
+
"Use /files to see your uploaded files and download them again."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
@app.on_message(filters.document | filters.photo)
|
| 56 |
+
async def handle_file(client: Client, message: Message):
|
| 57 |
+
"""Download any file or photo sent by the user, upload to dataset, clean disk."""
|
| 58 |
+
user_id = message.from_user.id
|
| 59 |
+
# Determine file object (document or largest photo)
|
| 60 |
+
file = message.document or (message.photo[-1] if message.photo else None)
|
| 61 |
+
if not file:
|
| 62 |
+
await message.reply_text("Please send a file or photo.")
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
# Download from Telegram
|
| 66 |
+
original_name = getattr(file, "file_name", None) or f"{file.file_unique_id}.file"
|
| 67 |
+
local_path = TEMP_DIR / f"{uuid.uuid4()}_{original_name}"
|
| 68 |
+
await message.download(file_id=file.file_id, file_name=str(local_path))
|
| 69 |
+
|
| 70 |
+
# Upload to Hugging Face dataset (folder per user)
|
| 71 |
+
remote_path = f"user_{user_id}/{local_path.name}"
|
| 72 |
+
logger.info(f"Uploading {local_path} to {DATASET_REPO}/{remote_path}")
|
| 73 |
+
hf_api.upload_file(
|
| 74 |
+
path_or_fileobj=str(local_path),
|
| 75 |
+
path_in_repo=remote_path,
|
| 76 |
+
repo_id=DATASET_REPO,
|
| 77 |
+
repo_type="dataset",
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# Clean local disk
|
| 81 |
+
os.remove(local_path)
|
| 82 |
+
|
| 83 |
+
await message.reply_text(
|
| 84 |
+
f"✅ File saved as `{original_name}`\nUse /files to list your uploads."
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
@app.on_message(filters.command("files"))
|
| 88 |
+
async def list_files(client: Client, message: Message):
|
| 89 |
+
"""Show an inline keyboard with all files uploaded by this user."""
|
| 90 |
+
user_id = message.from_user.id
|
| 91 |
+
folder = f"user_{user_id}"
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
files = hf_api.list_repo_tree(DATASET_REPO, path=folder, repo_type="dataset")
|
| 95 |
+
except Exception:
|
| 96 |
+
files = []
|
| 97 |
+
|
| 98 |
+
file_names = [f for f in files if not f.endswith("/")]
|
| 99 |
+
if not file_names:
|
| 100 |
+
await message.reply_text("You haven't uploaded any files yet.")
|
| 101 |
+
return
|
| 102 |
+
|
| 103 |
+
keyboard = []
|
| 104 |
+
for f in file_names:
|
| 105 |
+
display_name = f.rsplit("/", 1)[-1]
|
| 106 |
+
keyboard.append([InlineKeyboardButton(display_name, callback_data=f)])
|
| 107 |
+
|
| 108 |
+
await message.reply_text(
|
| 109 |
+
"📁 Your uploaded files (tap to download):",
|
| 110 |
+
reply_markup=InlineKeyboardMarkup(keyboard),
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
@app.on_callback_query()
|
| 114 |
+
async def download_file_callback(client: Client, callback_query: CallbackQuery):
|
| 115 |
+
"""Download the selected file from dataset and send it to the user."""
|
| 116 |
+
user_id = callback_query.from_user.id
|
| 117 |
+
file_path = callback_query.data
|
| 118 |
+
|
| 119 |
+
# Security: ensure file belongs to this user
|
| 120 |
+
if not file_path.startswith(f"user_{user_id}/"):
|
| 121 |
+
await callback_query.answer("⛔ You can only download your own files.", show_alert=True)
|
| 122 |
+
return
|
| 123 |
+
|
| 124 |
+
await callback_query.answer("Downloading...")
|
| 125 |
+
local_path = TEMP_DIR / f"dl_{uuid.uuid4()}_{file_path.split('/')[-1]}"
|
| 126 |
+
|
| 127 |
+
try:
|
| 128 |
+
downloaded_path = hf_hub_download(
|
| 129 |
+
repo_id=DATASET_REPO,
|
| 130 |
+
filename=file_path,
|
| 131 |
+
repo_type="dataset",
|
| 132 |
+
token=HF_TOKEN,
|
| 133 |
+
local_dir=TEMP_DIR,
|
| 134 |
+
local_dir_use_symlinks=False,
|
| 135 |
+
)
|
| 136 |
+
real_path = Path(downloaded_path)
|
| 137 |
+
|
| 138 |
+
# Send the file
|
| 139 |
+
await client.send_document(
|
| 140 |
+
chat_id=user_id,
|
| 141 |
+
document=str(real_path),
|
| 142 |
+
file_name=real_path.name,
|
| 143 |
+
)
|
| 144 |
+
except Exception as e:
|
| 145 |
+
logger.error(f"Download failed: {e}")
|
| 146 |
+
await callback_query.edit_message_text("❌ Failed to download the file. It may have been removed.")
|
| 147 |
+
return
|
| 148 |
+
finally:
|
| 149 |
+
if real_path and real_path.exists():
|
| 150 |
+
os.remove(real_path)
|
| 151 |
+
|
| 152 |
+
await callback_query.edit_message_text(f"📥 Sent: {real_path.name}")
|
| 153 |
+
|
| 154 |
+
# ---------- WEBHOOK ENDPOINT ----------
|
| 155 |
+
@fastapi_app.post(WEBHOOK_PATH)
|
| 156 |
+
async def telegram_webhook(request: Request):
|
| 157 |
+
"""Receive updates from Telegram and feed them to Pyrogram."""
|
| 158 |
+
try:
|
| 159 |
+
data = await request.json()
|
| 160 |
+
# Pyrogram expects an Update object (parsed from the JSON update)
|
| 161 |
+
update = Update.parse_raw(data) # data is already a dict, but parse_raw expects bytes/str
|
| 162 |
+
# Actually, Pyrogram v2: Update(**data) works.
|
| 163 |
+
# Use Update(**data) for a dict.
|
| 164 |
+
update_obj = Update(**data)
|
| 165 |
+
await app.dispatcher.process_update(update_obj)
|
| 166 |
+
except Exception as e:
|
| 167 |
+
logger.error(f"Error processing update: {e}")
|
| 168 |
+
return Response(status_code=200)
|
| 169 |
+
|
| 170 |
+
@fastapi_app.on_event("startup")
|
| 171 |
+
async def startup():
|
| 172 |
+
"""Set webhook and initialize Pyrogram."""
|
| 173 |
+
await app.initialize()
|
| 174 |
+
webhook_url = f"{WEBHOOK_URL}{WEBHOOK_PATH}"
|
| 175 |
+
await app.set_webhook(webhook_url)
|
| 176 |
+
logger.info(f"Webhook set to {webhook_url}")
|
| 177 |
+
|
| 178 |
+
@fastapi_app.on_event("shutdown")
|
| 179 |
+
async def shutdown():
|
| 180 |
+
await app.set_webhook("") # remove webhook
|
| 181 |
+
await app.stop()
|
| 182 |
+
|
| 183 |
+
@fastapi_app.get("/health")
|
| 184 |
+
async def health():
|
| 185 |
+
return {"status": "ok"}
|
| 186 |
+
|
| 187 |
+
# ---------- MAIN ----------
|
| 188 |
+
if __name__ == "__main__":
|
| 189 |
+
uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)
|
bot.py
DELETED
|
@@ -1,243 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import asyncio
|
| 3 |
-
import tempfile
|
| 4 |
-
import time
|
| 5 |
-
import logging
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
|
| 8 |
-
from pyrogram import Client, filters
|
| 9 |
-
from pyrogram.types import Message
|
| 10 |
-
from huggingface_hub import HfApi, hf_hub_download, login
|
| 11 |
-
from aiohttp import web
|
| 12 |
-
|
| 13 |
-
# ---------- Logging ----------
|
| 14 |
-
logging.basicConfig(
|
| 15 |
-
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
| 16 |
-
level=logging.INFO,
|
| 17 |
-
)
|
| 18 |
-
logger = logging.getLogger(__name__)
|
| 19 |
-
|
| 20 |
-
# ---------- Configuration ----------
|
| 21 |
-
API_ID = int(os.getenv("API_ID"))
|
| 22 |
-
API_HASH = os.getenv("API_HASH")
|
| 23 |
-
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
| 24 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 25 |
-
DATASET_REPO = os.getenv("HF_DATASET_REPO", "Cxops/Bzxv")
|
| 26 |
-
|
| 27 |
-
# ---------- Hugging Face setup ----------
|
| 28 |
-
login(token=HF_TOKEN)
|
| 29 |
-
hf_api = HfApi()
|
| 30 |
-
try:
|
| 31 |
-
hf_api.create_repo(repo_id=DATASET_REPO, repo_type="dataset", exist_ok=True)
|
| 32 |
-
logger.info(f"Dataset repo '{DATASET_REPO}' ready.")
|
| 33 |
-
except Exception as e:
|
| 34 |
-
logger.error(f"Failed to create/access dataset: {e}")
|
| 35 |
-
raise
|
| 36 |
-
|
| 37 |
-
# ---------- Pyrogram client ----------
|
| 38 |
-
app = Client(
|
| 39 |
-
"telegram_file_bot",
|
| 40 |
-
api_id=API_ID,
|
| 41 |
-
api_hash=API_HASH,
|
| 42 |
-
bot_token=BOT_TOKEN,
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
# ---------- Helper: format sizes & speed ----------
|
| 46 |
-
def format_size(size: int) -> str:
|
| 47 |
-
if size >= 1_000_000_000:
|
| 48 |
-
return f"{size / 1_000_000_000:.2f} GB"
|
| 49 |
-
elif size >= 1_000_000:
|
| 50 |
-
return f"{size / 1_000_000:.2f} MB"
|
| 51 |
-
elif size >= 1_000:
|
| 52 |
-
return f"{size / 1_000:.2f} KB"
|
| 53 |
-
return f"{size} B"
|
| 54 |
-
|
| 55 |
-
def format_speed(bytes_per_sec: float) -> str:
|
| 56 |
-
if bytes_per_sec >= 1_000_000:
|
| 57 |
-
return f"{bytes_per_sec / 1_000_000:.2f} MB/s"
|
| 58 |
-
elif bytes_per_sec >= 1_000:
|
| 59 |
-
return f"{bytes_per_sec / 1_000:.2f} KB/s"
|
| 60 |
-
return f"{bytes_per_sec:.2f} B/s"
|
| 61 |
-
|
| 62 |
-
# ---------- Helper: progress callback ----------
|
| 63 |
-
async def progress_callback(
|
| 64 |
-
current: int,
|
| 65 |
-
total: int,
|
| 66 |
-
message: Message,
|
| 67 |
-
start_time: float,
|
| 68 |
-
last_update: dict,
|
| 69 |
-
):
|
| 70 |
-
"""Update progress message every 3 seconds, showing speed and percentage."""
|
| 71 |
-
now = time.time()
|
| 72 |
-
if (total > 0 and (now - last_update["time"] >= 3)) or current == total:
|
| 73 |
-
elapsed = now - start_time
|
| 74 |
-
speed = current / elapsed if elapsed > 0 else 0
|
| 75 |
-
percent = (current / total) * 100
|
| 76 |
-
text = (
|
| 77 |
-
f"📥 Progress: {percent:.1f}%\n"
|
| 78 |
-
f"⚡ {format_speed(speed)} | {format_size(current)} / {format_size(total)}"
|
| 79 |
-
)
|
| 80 |
-
try:
|
| 81 |
-
await message.edit_text(text)
|
| 82 |
-
except Exception:
|
| 83 |
-
pass
|
| 84 |
-
last_update["time"] = now
|
| 85 |
-
|
| 86 |
-
# ---------- HF helpers ----------
|
| 87 |
-
def upload_to_hub(file_path: str, file_name: str) -> bool:
|
| 88 |
-
try:
|
| 89 |
-
hf_api.upload_file(
|
| 90 |
-
path_or_fileobj=file_path,
|
| 91 |
-
path_in_repo=f"files/{file_name}",
|
| 92 |
-
repo_id=DATASET_REPO,
|
| 93 |
-
repo_type="dataset",
|
| 94 |
-
commit_message=f"Upload {file_name}",
|
| 95 |
-
)
|
| 96 |
-
logger.info(f"Uploaded '{file_name}' to dataset.")
|
| 97 |
-
return True
|
| 98 |
-
except Exception as e:
|
| 99 |
-
logger.error(f"Upload failed: {e}")
|
| 100 |
-
return False
|
| 101 |
-
|
| 102 |
-
def download_from_hub(file_name: str) -> str | None:
|
| 103 |
-
try:
|
| 104 |
-
return hf_hub_download(
|
| 105 |
-
repo_id=DATASET_REPO,
|
| 106 |
-
filename=f"files/{file_name}",
|
| 107 |
-
repo_type="dataset",
|
| 108 |
-
cache_dir=tempfile.gettempdir(),
|
| 109 |
-
)
|
| 110 |
-
except Exception as e:
|
| 111 |
-
logger.error(f"Download failed: {e}")
|
| 112 |
-
return None
|
| 113 |
-
|
| 114 |
-
# ---------- Command handlers ----------
|
| 115 |
-
@app.on_message(filters.command("start"))
|
| 116 |
-
async def start_cmd(client: Client, message: Message):
|
| 117 |
-
await message.reply(
|
| 118 |
-
"🤖 **Telegram ↔ Hugging Face File Bot**\n\n"
|
| 119 |
-
"Send me any file and I'll store it in your dataset.\n"
|
| 120 |
-
"Use /list to see all stored files.\n"
|
| 121 |
-
"Use /get <filename> to retrieve a file."
|
| 122 |
-
)
|
| 123 |
-
|
| 124 |
-
@app.on_message(filters.command("list"))
|
| 125 |
-
async def list_cmd(client: Client, message: Message):
|
| 126 |
-
try:
|
| 127 |
-
files = hf_api.list_repo_files(repo_id=DATASET_REPO, repo_type="dataset")
|
| 128 |
-
stored = [f.replace("files/", "") for f in files if f.startswith("files/")]
|
| 129 |
-
if not stored:
|
| 130 |
-
await message.reply("📂 No files stored yet.")
|
| 131 |
-
else:
|
| 132 |
-
await message.reply("📁 **Stored files:**\n" + "\n".join(stored))
|
| 133 |
-
except Exception as e:
|
| 134 |
-
await message.reply(f"❌ Error listing files: {e}")
|
| 135 |
-
|
| 136 |
-
@app.on_message(filters.command("get"))
|
| 137 |
-
async def get_cmd(client: Client, message: Message):
|
| 138 |
-
args = message.text.split(maxsplit=1)
|
| 139 |
-
if len(args) < 2:
|
| 140 |
-
await message.reply("Usage: `/get <filename>`")
|
| 141 |
-
return
|
| 142 |
-
|
| 143 |
-
file_name = args[1].strip()
|
| 144 |
-
status_msg = await message.reply("🔍 Fetching file from dataset...")
|
| 145 |
-
|
| 146 |
-
local_path = download_from_hub(file_name)
|
| 147 |
-
if local_path is None:
|
| 148 |
-
await status_msg.edit_text(f"❌ File `{file_name}` not found.")
|
| 149 |
-
return
|
| 150 |
-
|
| 151 |
-
await status_msg.edit_text(f"📤 Uploading `{file_name}` to Telegram...")
|
| 152 |
-
|
| 153 |
-
start_time = time.time()
|
| 154 |
-
last_update = {"time": 0}
|
| 155 |
-
|
| 156 |
-
try:
|
| 157 |
-
await client.send_document(
|
| 158 |
-
chat_id=message.chat.id,
|
| 159 |
-
document=local_path,
|
| 160 |
-
file_name=file_name,
|
| 161 |
-
progress=progress_callback,
|
| 162 |
-
progress_args=(status_msg, start_time, last_update),
|
| 163 |
-
)
|
| 164 |
-
elapsed = time.time() - start_time
|
| 165 |
-
if os.path.exists(local_path):
|
| 166 |
-
size = os.path.getsize(local_path)
|
| 167 |
-
await status_msg.edit_text(
|
| 168 |
-
f"✅ Sent `{file_name}` ({format_size(size)}) in {elapsed:.1f}s"
|
| 169 |
-
)
|
| 170 |
-
else:
|
| 171 |
-
await status_msg.edit_text(f"✅ Sent `{file_name}`.")
|
| 172 |
-
except Exception as e:
|
| 173 |
-
await status_msg.edit_text(f"❌ Could not send file: {e}")
|
| 174 |
-
finally:
|
| 175 |
-
if os.path.exists(local_path):
|
| 176 |
-
os.unlink(local_path)
|
| 177 |
-
|
| 178 |
-
@app.on_message(filters.document)
|
| 179 |
-
async def handle_document(client: Client, message: Message):
|
| 180 |
-
doc = message.document
|
| 181 |
-
file_name = doc.file_name or f"file_{message.id}.bin"
|
| 182 |
-
|
| 183 |
-
progress_msg = await message.reply("📥 Starting download...")
|
| 184 |
-
start_time = time.time()
|
| 185 |
-
last_update = {"time": 0}
|
| 186 |
-
|
| 187 |
-
tmp = tempfile.NamedTemporaryFile(delete=False)
|
| 188 |
-
tmp_path = tmp.name
|
| 189 |
-
try:
|
| 190 |
-
await message.download(
|
| 191 |
-
file_name=tmp_path,
|
| 192 |
-
progress=progress_callback,
|
| 193 |
-
progress_args=(progress_msg, start_time, last_update),
|
| 194 |
-
)
|
| 195 |
-
|
| 196 |
-
if os.path.exists(tmp_path):
|
| 197 |
-
size = os.path.getsize(tmp_path)
|
| 198 |
-
elapsed = time.time() - start_time
|
| 199 |
-
speed = size / elapsed if elapsed > 0 else 0
|
| 200 |
-
await progress_msg.edit_text(
|
| 201 |
-
f"✅ Downloaded {format_size(size)} in {elapsed:.1f}s "
|
| 202 |
-
f"({format_speed(speed)})\n"
|
| 203 |
-
"⏳ Uploading to dataset..."
|
| 204 |
-
)
|
| 205 |
-
else:
|
| 206 |
-
await progress_msg.edit_text("⚠️ Download finished but file missing.")
|
| 207 |
-
|
| 208 |
-
success = upload_to_hub(tmp_path, file_name)
|
| 209 |
-
if success:
|
| 210 |
-
await progress_msg.edit_text(
|
| 211 |
-
f"✅ File `{file_name}` stored in dataset."
|
| 212 |
-
)
|
| 213 |
-
else:
|
| 214 |
-
await progress_msg.edit_text("❌ Failed to upload to dataset.")
|
| 215 |
-
except Exception as e:
|
| 216 |
-
await progress_msg.edit_text(f"❌ Download failed: {e}")
|
| 217 |
-
finally:
|
| 218 |
-
if os.path.exists(tmp_path):
|
| 219 |
-
os.unlink(tmp_path)
|
| 220 |
-
|
| 221 |
-
# ---------- Health check server (port 7860) ----------
|
| 222 |
-
async def health_handler(request):
|
| 223 |
-
return web.Response(text="Bot is running")
|
| 224 |
-
|
| 225 |
-
async def start_health_server():
|
| 226 |
-
app_web = web.Application()
|
| 227 |
-
app_web.router.add_get("/", health_handler)
|
| 228 |
-
runner = web.AppRunner(app_web)
|
| 229 |
-
await runner.setup()
|
| 230 |
-
site = web.TCPSite(runner, "0.0.0.0", 7860)
|
| 231 |
-
await site.start()
|
| 232 |
-
logger.info("Health server started on port 7860")
|
| 233 |
-
|
| 234 |
-
# ---------- Main ----------
|
| 235 |
-
async def main():
|
| 236 |
-
await app.start()
|
| 237 |
-
logger.info("Pyrogram bot client started")
|
| 238 |
-
await start_health_server()
|
| 239 |
-
# Keep the bot alive (replaces app.idle() which doesn't exist)
|
| 240 |
-
await asyncio.Event().wait()
|
| 241 |
-
|
| 242 |
-
if __name__ == "__main__":
|
| 243 |
-
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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