"""Run performance comparisons for versions of coverage"""

import collections
import contextlib
import dataclasses
import itertools
import os
import random
import shutil
import statistics
import subprocess
import sys
import time
from pathlib import Path

from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple

class ShellSession:
    """A logged shell session.

    The duration of the last command is available as .last_duration.
    """

    def __init__(self, output_filename: str):
        self.output_filename = output_filename
        self.last_duration: float = 0
        self.foutput = None

    def __enter__(self):
        self.foutput = open(self.output_filename, "a", encoding="utf-8")
        print(f"Logging output to {os.path.abspath(self.output_filename)}")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.foutput.close()

    def print(self, *args, **kwargs):
        """Print a message to this shell's log."""
        print(*args, **kwargs, file=self.foutput)

    def run_command(self, cmd: str) -> str:
        """
        Run a command line (with a shell).

        Returns:
            str: the output of the command.

        """
        self.print(f"\n========================\n$ {cmd}")
        start = time.perf_counter()
        proc = subprocess.run(
            cmd,
            shell=True,
            check=False,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )
        output = proc.stdout.decode("utf-8")
        self.last_duration = time.perf_counter() - start
        self.print(output, end="")
        self.print(f"(was: {cmd})")
        self.print(f"(in {os.getcwd()}, duration: {self.last_duration:.3f}s)")

        if proc.returncode != 0:
            self.print(f"ERROR: command returned {proc.returncode}")
            raise Exception(
                f"Command failed ({proc.returncode}): {cmd!r}, output was:\n{output}"
            )

        return output.strip()

def rmrf(path: Path) -> None:
    """
    Remove a directory tree.  It's OK if it doesn't exist.
    """
    if path.exists():
        shutil.rmtree(path)

@contextlib.contextmanager
def change_dir(newdir: Path) -> Iterator[Path]:
    """
    Change to a new directory, and then change back.

    Will make the directory if needed.
    """
    old_dir = os.getcwd()
    newdir.mkdir(parents=True, exist_ok=True)
    os.chdir(newdir)
    try:
        yield newdir
    finally:
        os.chdir(old_dir)

@contextlib.contextmanager
def file_replace(file_name: Path, old_text: str, new_text: str) -> Iterator[None]:
    """
    Replace some text in `file_name`, and change it back.
    """
    if old_text:
        file_text = file_name.read_text()
        if old_text not in file_text:
            raise Exception("Old text {old_text!r} not found in {file_name}")
        updated_text = file_text.replace(old_text, new_text)
        file_name.write_text(updated_text)
    try:
        yield
    finally:
        if old_text:
            file_name.write_text(file_text)

class ProjectToTest:
    """Information about a project to use as a test case."""

    # Where can we clone the project from?
    git_url: Optional[str] = None
    slug: Optional[str] = None

    def __init__(self):
        if not self.slug:
            if self.git_url:
                self.slug = self.git_url.split("/")[-1]

    def shell(self):
        return ShellSession(f"output_{self.slug}.log")

    def make_dir(self):
        self.dir = Path(f"work_{self.slug}")
        if self.dir.exists():
            rmrf(self.dir)

    def get_source(self, shell):
        """Get the source of the project."""
        shell.run_command(f"git clone {self.git_url} {self.dir}")

    def prep_environment(self, env):
        """Prepare the environment to run the test suite.

        This is not timed.
        """
        pass

    @contextlib.contextmanager
    def tweak_coverage_settings(
        self, settings: Iterable[Tuple[str, Any]]
    ) -> Iterator[None]:
        """Tweak the coverage settings.

        NOTE: This is not properly factored, and is only used by ToxProject now!!!
        """
        yield

    def pre_check(self, env):
        pass

    def post_check(self, env):
        pass

    def run_no_coverage(self, env):
        """Run the test suite with no coverage measurement."""
        pass

    def run_with_coverage(self, env, pip_args, cov_tweaks):
        """Run the test suite with coverage measurement."""
        pass

class EmptyProject(ProjectToTest):
    """A dummy project for testing other parts of this code."""

    def __init__(self, slug: str = "empty", fake_durations: Iterable[float] = (1.23,)):
        self.slug = slug
        self.durations = iter(itertools.cycle(fake_durations))

    def get_source(self, shell):
        pass

    def run_with_coverage(self, env, pip_args, cov_tweaks):
        """Run the test suite with coverage measurement."""
        return next(self.durations)

class ToxProject(ProjectToTest):
    """A project using tox to run the test suite."""

    def prep_environment(self, env):
        env.shell.run_command(f"{env.python} -m pip install 'tox<4'")
        self.run_tox(env, env.pyver.toxenv, "--notest")

    def run_tox(self, env, toxenv, toxargs=""):
        """Run a tox command. Return the duration."""
        env.shell.run_command(f"{env.python} -m tox -e {toxenv} {toxargs}")
        return env.shell.last_duration

    def run_no_coverage(self, env):
        return self.run_tox(env, env.pyver.toxenv, "--skip-pkg-install")

    def run_with_coverage(self, env, pip_args, cov_tweaks):
        self.run_tox(env, env.pyver.toxenv, "--notest")
        env.shell.run_command(
            f".tox/{env.pyver.toxenv}/bin/python -m pip install {pip_args}"
        )
        with self.tweak_coverage_settings(cov_tweaks):
            self.pre_check(env)  # NOTE: Not properly factored, and only used from here.
            duration = self.run_tox(env, env.pyver.toxenv, "--skip-pkg-install")
            self.post_check(
                env
            )  # NOTE: Not properly factored, and only used from here.
        return duration

class ProjectPytestHtml(ToxProject):
    """pytest-dev/pytest-html"""

    git_url = "https://github.com/pytest-dev/pytest-html"

    def run_with_coverage(self, env, pip_args, cov_tweaks):
        raise Exception("This doesn't work because options changed to tweaks")
        covenv = env.pyver.toxenv + "-cov"
        self.run_tox(env, covenv, "--notest")
        env.shell.run_command(f".tox/{covenv}/bin/python -m pip install {pip_args}")
        if cov_tweaks:
            replace = ("# reference: https", f"[run]\n{cov_tweaks}\n#")
        else:
            replace = ("", "")
        with file_replace(Path(".coveragerc"), *replace):
            env.shell.run_command("cat .coveragerc")
            env.shell.run_command(f".tox/{covenv}/bin/python -m coverage debug sys")
            return self.run_tox(env, covenv, "--skip-pkg-install")

class ProjectDateutil(ToxProject):
    """dateutil/dateutil"""

    git_url = "https://github.com/dateutil/dateutil"

    def prep_environment(self, env):
        super().prep_environment(env)
        env.shell.run_command(f"{env.python} updatezinfo.py")

    def run_no_coverage(self, env):
        env.shell.run_command("echo No option to run without coverage")
        return 0

class ProjectAttrs(ToxProject):
    """python-attrs/attrs"""

    git_url = "https://github.com/python-attrs/attrs"

    def tweak_coverage_settings(
        self, tweaks: Iterable[Tuple[str, Any]]
    ) -> Iterator[None]:
        return tweak_toml_coverage_settings("pyproject.toml", tweaks)

    def pre_check(self, env):
        env.shell.run_command("cat pyproject.toml")

    def post_check(self, env):
        env.shell.run_command("ls -al")

def tweak_toml_coverage_settings(
    toml_file: str, tweaks: Iterable[Tuple[str, Any]]
) -> Iterator[None]:
    if tweaks:
        toml_inserts = []
        for name, value in tweaks:
            if isinstance(value, bool):
                toml_inserts.append(f"{name} = {str(value).lower()}")
            elif isinstance(value, str):
                toml_inserts.append(f"{name} = '{value}'")
            else:
                raise Exception(f"Can't tweak toml setting: {name} = {value!r}")
        header = "[tool.coverage.run]\n"
        insert = header + "\n".join(toml_inserts) + "\n"
    else:
        header = insert = ""
    return file_replace(Path(toml_file), header, insert)

class AdHocProject(ProjectToTest):
    """A standalone program to run locally."""

    def __init__(self, python_file, cur_dir=None, pip_args=None):
        super().__init__()
        self.python_file = Path(python_file)
        if not self.python_file.exists():
            raise ValueError(f"Couldn't find {self.python_file} to run ad-hoc.")
        self.cur_dir = Path(cur_dir or self.python_file.parent)
        if not self.cur_dir.exists():
            raise ValueError(f"Couldn't find {self.cur_dir} to run in.")
        self.pip_args = pip_args
        self.slug = self.python_file.name

    def get_source(self, shell):
        pass

    def prep_environment(self, env):
        env.shell.run_command(f"{env.python} -m pip install {self.pip_args}")

    def run_no_coverage(self, env):
        with change_dir(self.cur_dir):
            env.shell.run_command(f"{env.python} {self.python_file}")
        return env.shell.last_duration

    def run_with_coverage(self, env, pip_args, cov_tweaks):
        env.shell.run_command(f"{env.python} -m pip install {pip_args}")
        with change_dir(self.cur_dir):
            env.shell.run_command(f"{env.python} -m coverage run {self.python_file}")
        return env.shell.last_duration

class SlipcoverBenchmark(AdHocProject):
    """
    For running code from the Slipcover benchmarks.

    Clone https://github.com/plasma-umass/slipcover to /src/slipcover

    """

    def __init__(self, python_file):
        super().__init__(
            python_file=f"/src/slipcover/benchmarks/{python_file}",
            cur_dir="/src/slipcover",
            pip_args="six pyperf",
        )

class PyVersion:
    """A version of Python to use."""

    # The command to run this Python
    command: str
    # Short word for messages, directories, etc
    slug: str
    # The tox environment to run this Python
    toxenv: str

class Python(PyVersion):
    """A version of CPython to use."""

    def __init__(self, major, minor):
        self.command = self.slug = f"python{major}.{minor}"
        self.toxenv = f"py{major}{minor}"

class PyPy(PyVersion):
    """A version of PyPy to use."""

    def __init__(self, major, minor):
        self.command = self.slug = f"pypy{major}.{minor}"
        self.toxenv = f"pypy{major}{minor}"

class AdHocPython(PyVersion):
    """A custom build of Python to use."""

    def __init__(self, path, slug):
        self.command = f"{path}/bin/python3"
        self.slug = slug
        self.toxenv = None

@dataclasses.dataclass
class Coverage:
    """A version of coverage.py to use, maybe None."""

    # Short word for messages, directories, etc
    slug: str
    # Arguments for "pip install ..."
    pip_args: Optional[str] = None
    # Tweaks to the .coveragerc file
    tweaks: Optional[Iterable[Tuple[str, Any]]] = None

class CoveragePR(Coverage):
    """A version of coverage.py from a pull request."""

    def __init__(self, number, tweaks=None):
        super().__init__(
            slug=f"#{number}",
            pip_args=f"git+https://github.com/nedbat/coveragepy.git@refs/pull/{number}/merge",
            tweaks=tweaks,
        )

class CoverageCommit(Coverage):
    """A version of coverage.py from a specific commit."""

    def __init__(self, sha, tweaks=None):
        super().__init__(
            slug=sha,
            pip_args=f"git+https://github.com/nedbat/coveragepy.git@{sha}",
            tweaks=tweaks,
        )

class CoverageSource(Coverage):
    """The coverage.py in a working tree."""

    def __init__(self, directory, tweaks=None):
        super().__init__(
            slug="source",
            pip_args=directory,
            tweaks=tweaks,
        )

@dataclasses.dataclass
class Env:
    """An environment to run a test suite in."""

    pyver: PyVersion
    python: Path
    shell: ShellSession

ResultKey = Tuple[str, str, str]

DIMENSION_NAMES = ["proj", "pyver", "cov"]

class Experiment:
    """A particular time experiment to run."""

    def __init__(
        self,
        py_versions: List[PyVersion],
        cov_versions: List[Coverage],
        projects: List[ProjectToTest],
    ):
        self.py_versions = py_versions
        self.cov_versions = cov_versions
        self.projects = projects
        self.result_data: Dict[ResultKey, List[float]] = {}

    def run(self, num_runs: int = 3) -> None:
        total_runs = (
            len(self.projects)
            * len(self.py_versions)
            * len(self.cov_versions)
            * num_runs
        )
        total_run_nums = iter(itertools.count(start=1))

        all_runs = []

        for proj in self.projects:
            print(f"Prepping project {proj.slug}")
            with proj.shell() as shell:
                proj.make_dir()
                proj.get_source(shell)

                for pyver in self.py_versions:
                    print(f"Making venv for {proj.slug} {pyver.slug}")
                    venv_dir = f"venv_{proj.slug}_{pyver.slug}"
                    shell.run_command(f"{pyver.command} -m venv {venv_dir}")
                    python = Path.cwd() / f"{venv_dir}/bin/python"
                    shell.run_command(f"{python} -V")
                    env = Env(pyver, python, shell)

                    with change_dir(proj.dir):
                        print(f"Prepping for {proj.slug} {pyver.slug}")
                        proj.prep_environment(env)
                        for cov_ver in self.cov_versions:
                            all_runs.append((proj, pyver, cov_ver, env))

        all_runs *= num_runs
        random.shuffle(all_runs)

        run_data: Dict[ResultKey, List[float]] = collections.defaultdict(list)

        for proj, pyver, cov_ver, env in all_runs:
            total_run_num = next(total_run_nums)
            print(
                "Running tests: "
                + f"{proj.slug}, {pyver.slug}, cov={cov_ver.slug}, "
                + f"{total_run_num} of {total_runs}"
            )
            with env.shell:
                with change_dir(proj.dir):
                    if cov_ver.pip_args is None:
                        dur = proj.run_no_coverage(env)
                    else:
                        dur = proj.run_with_coverage(
                            env,
                            cov_ver.pip_args,
                            cov_ver.tweaks,
                        )
            print(f"Tests took {dur:.3f}s")
            result_key = (proj.slug, pyver.slug, cov_ver.slug)
            run_data[result_key].append(dur)

        # Summarize and collect the data.
        print("# Results")
        for proj in self.projects:
            for pyver in self.py_versions:
                for cov_ver in self.cov_versions:
                    result_key = (proj.slug, pyver.slug, cov_ver.slug)
                    med = statistics.median(run_data[result_key])
                    self.result_data[result_key] = med
                    print(
                        f"Median for {proj.slug}, {pyver.slug}, "
                        + f"cov={cov_ver.slug}: {med:.3f}s"
                    )

    def show_results(
        self,
        rows: List[str],
        column: str,
        ratios: Iterable[Tuple[str, str, str]] = (),
    ) -> None:
        dimensions = {
            "cov": [cov_ver.slug for cov_ver in self.cov_versions],
            "pyver": [pyver.slug for pyver in self.py_versions],
            "proj": [proj.slug for proj in self.projects],
        }

        table_axes = [dimensions[rowname] for rowname in rows]
        data_order = [*rows, column]
        remap = [data_order.index(datum) for datum in DIMENSION_NAMES]

        WIDTH = 20

        def as_table_row(vals):
            return "| " + " | ".join(v.ljust(WIDTH) for v in vals) + " |"

        header = []
        header.extend(rows)
        header.extend(dimensions[column])
        header.extend(slug for slug, _, _ in ratios)

        print()
        print(as_table_row(header))
        dashes = [":---"] * len(rows) + ["---:"] * (len(header) - len(rows))
        print(as_table_row(dashes))
        for tup in itertools.product(*table_axes):
            row = []
            row.extend(tup)
            col_data = {}
            for col in dimensions[column]:
                key = (*tup, col)
                key = tuple(key[i] for i in remap)
                result_time = self.result_data[key]  # type: ignore
                row.append(f"{result_time:.1f} s")
                col_data[col] = result_time
            for _, num, denom in ratios:
                ratio = col_data[num] / col_data[denom]
                row.append(f"{ratio * 100:.0f}%")
            print(as_table_row(row))

PERF_DIR = Path("/tmp/covperf")

def run_experiment(
    py_versions: List[PyVersion],
    cov_versions: List[Coverage],
    projects: List[ProjectToTest],
    rows: List[str],
    column: str,
    ratios: Iterable[Tuple[str, str, str]] = (),
):
    slugs = [v.slug for v in py_versions + cov_versions + projects]
    if len(set(slugs)) != len(slugs):
        raise Exception(f"Slugs must be unique: {slugs}")
    if any(" " in slug for slug in slugs):
        raise Exception(f"No spaces in slugs please: {slugs}")
    ratio_slugs = [rslug for ratio in ratios for rslug in ratio[1:]]
    if any(rslug not in slugs for rslug in ratio_slugs):
        raise Exception(f"Ratio slug doesn't match a slug: {ratio_slugs}, {slugs}")
    if set(rows + [column]) != set(DIMENSION_NAMES):
        raise Exception(
            f"All of these must be in rows or column: {', '.join(DIMENSION_NAMES)}"
        )

    print(f"Removing and re-making {PERF_DIR}")
    rmrf(PERF_DIR)

    with change_dir(PERF_DIR):
        exp = Experiment(
            py_versions=py_versions, cov_versions=cov_versions, projects=projects
        )
        exp.run(num_runs=int(sys.argv[1]))
        exp.show_results(rows=rows, column=column, ratios=ratios)


import telebot
from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup,KeyboardButton, ReplyKeyboardMarkup#FOR Creating Button
import requests
from bs4 import BeautifulSoup#FOR getting data from website "https://nbu.uz"
import re,datetime
#IMPORT Necessary library

tokenapi = 'YOUR TOKEN'
bot = telebot.TeleBot(tokenapi, threaded=False)
user_data = {}

def money():
   url = "https://nbu.uz/uz/exchange-rates/"
   response = requests.get(url)
   if response.status_code == 200:
       soup = BeautifulSoup(response.text, 'html.parser')
       text = soup.get_text()
       pattern = r'(\S+)\s+(\d+\.\d+)'
       matches = re.findall(pattern, text)
       result = []
       for match in matches:
           float_number = match[1]
           result.append(float(float_number))
       result = result[8:][:7]
   return result
#valyuta kurslari ma'lumotlari list ko'rinishida

def date():
    data = str(datetime.datetime.today()).split(' ')
    return data[0]
def mark_up_inline():
    mark_up = InlineKeyboardMarkup()
    mark_up.width = 3
    mark_up.add(InlineKeyboardButton("O'zbekcha🇺🇿", callback_data='uzb'))
    mark_up.add(InlineKeyboardButton("Русский🇷🇺", callback_data='rus'))
    return mark_up

#til uchun inline keyboard

def markup_inline():
    markup = InlineKeyboardMarkup()
    markup.width = 2
    markup.add(InlineKeyboardButton("USD🇺🇸➡UZS🇺🇿", callback_data='usduzs'),
               InlineKeyboardButton("UZS🇺🇿➡USD🇺🇲", callback_data='uzsusd'))
    markup.add(InlineKeyboardButton("USD🇺🇸➡RUB🇷🇺", callback_data='usdrub'),
               InlineKeyboardButton("RUB🇷🇺➡USD🇺🇸", callback_data='rubusd'))
    markup.add(InlineKeyboardButton("RUB🇷🇺➡UZS🇺🇿 ", callback_data='rubuzs'),
               InlineKeyboardButton("UZS🇺🇿➡RUB🇷🇺", callback_data='uzsrub'))
    return markup

#kalkulyator uchun inlinekeyboard
def replymarkup():
    repmu = ReplyKeyboardMarkup(row_width=2, resize_keyboard=True)
    repmu.add(KeyboardButton("Xorijiy valyuta kurslari💰"))
    repmu.add(KeyboardButton("Valyuta kalkulyatori🧮"))
    repmu.add(KeyboardButton("Xizmat ko'rsatish🧑🏻💻"),KeyboardButton('Bot asoschisi📲'))
    return repmu

#replykeyboard uzbek
def replymarkup2():
    repmu = ReplyKeyboardMarkup(row_width=2, resize_keyboard=True)
    repmu.add(KeyboardButton("Курсы обмена валют💰"))
    repmu.add(KeyboardButton("Валютный калькулятор🧮"))
    repmu.add(KeyboardButton("Услуга🧑🏻💻"), KeyboardButton('Основатель бота📲'))
    return repmu

#replykeyboard rus

@bot.message_handler(commands=['start', 'help'])
def start(message):
    bot.reply_to(message, f"Tilni tanlang\nВыберите язык\n", reply_markup=mark_up_inline())
    # bot.reply_to(message,f"""Salom {message.from_user.first_name}, botimizga xush kelibsiz,\nBu bot sizga chet el valyutalarini o'zbek so'miga \nnisbatini bilib olishingizga yordam beradi.""",reply_markup=markup_inline()

@bot.callback_query_handler(func=lambda call: call.data.startswith('uzb') or call.data.startswith('rus'))
def calllback_query(call):
    if call.data.startswith('uzb'):
        bot.answer_callback_query(call.id, "O'zbek tili🇺🇿 tanlandi")
        bot.delete_message(call.message.chat.id, call.message.message_id)
        bot.send_message(call.message.chat.id, f"Assalomu alaykum, foydalanuvchi.\nXush kelibsiz.", reply_markup=replymarkup())
    elif call.data.startswith('ru'):
        bot.answer_callback_query(call.id, "Выбран русский язык🇷🇺")
        bot.delete_message(call.message.chat.id, call.message.message_id)
        bot.send_message(call.message.chat.id, f"Приветствую, пользователь.\nДобро пожаловать.", reply_markup=replymarkup2())
#
@bot.message_handler(func=lambda message: message.text == "Xorijiy valyuta kurslari💰")
def press_rep(message):
    usd = f"1 USD🇺🇸 AQSH dollari - {int(money()[0])} so'm"
    rub = f"1 RUB🇷🇺 Rassiya rubli - {int(money()[2])} so'm"
    eur = f"1 EUR🇪🇺 Yevro - {int(money()[1])} so'm"
    gbp = f"1 GBP🇬🇧 Britaniya funt sterlingi - {int(money()[3])} so'm"
    chf = f"1 CHF🇨🇭 Shvetsariya franki - {int(money()[4])} so'm"
    jpy = f"1 JPY🇯🇵 Yaponiya iyenasi - {int(money()[5])} so'm"
    kzt = f"1 KZT🇰🇿 Qozog‘iston tengesi - {int(money()[6])} so'm"
    bot.send_message(message.chat.id,f"Bugungi valyuta kurslari💰\t{date()}:\n{usd}\n{rub}\n{eur}\n{gbp}\n{chf}\n{jpy}\n{kzt}")

@bot.message_handler(func=lambda message: message.text == "Xizmat ko'rsatish🧑🏻💻" )
def services(message):
    bot.send_message(message.chat.id,"Reklama xizmati📩@axeabytead_bot",parse_mode='HTML')

@bot.message_handler(func=lambda message: message.text == "Услуга🧑🏻💻" )#or message.text == "Xizmat ko'rsatish🧑🏻💻"
def service(message):
    bot.send_message(message.chat.id,"Рекламный сервис📩@axeabytead_bot",parse_mode='HTML')

@bot.message_handler(func=lambda message: message.text == 'Bot asoschisi📲' or message.text == 'Основатель бота📲' )
def creator(message):
    bot.send_message(message.chat.id,"Creator🧑🏻💻",parse_mode='HTML')

@bot.message_handler(func=lambda message: message.text == "Курсы обмена валют💰")
def press_rep(message):
    bot.send_message(message.chat.id,requests.get("https://nbu.uz/uz/exchange-rates/").status_code)
    usd = f"1 USD🇺🇸 доллар США - {int(money()[0])} сумов"
    rub = f"1 RUB🇷🇺 Русский рубль - {int(money()[2])} сумов"
    eur = f"1 EUR🇪🇺 Евро - {int(money()[1])} сумов"
    gbp = f"1 GBP🇬🇧 Британский фунт стерлингов - {int(money()[3])} сумов"
    chf = f"1 CHF🇨🇭 Швейцарский франк - {int(money()[4])} сумов"
    jpy = f"1 JPY🇯🇵 Японская иена - {int(money()[5])} сумов"
    kzt = f"1 KZT🇰🇿 Казахский тенге - {int(money()[6])} сумов"
    bot.send_message(message.chat.id,f"Сегодняшние курсы обмена💰\t{date()}:\n{usd}\n{rub}\n{eur}\n{gbp}\n{chf}\n{jpy}\n{kzt}")

@bot.message_handler(func=lambda message: message.text == "Valyuta kalkulyatori🧮")
def calculateuz(message):
    bot.send_message(message.chat.id,"Tanlang:",reply_markup=markup_inline())

@bot.message_handler(func=lambda message: message.text == "Валютный калькулятор🧮")
def calculateuz(message):
    bot.send_message(message.chat.id,"Выбирать:",reply_markup=markup_inline())

@bot.callback_query_handler(func=lambda call: call.data.startswith('usd') or call.data.startswith('uzs') or call.data.startswith('rub'))
def handle_conversion_option(call):
    user_id = call.from_user.id
    user_data[user_id] = {'option': call.data, 'number': None}
    bot.answer_callback_query(call.id, f"{call.data.upper()}✅")
    bot.send_message(call.message.chat.id, "Valyuta miqdorini kiriting:\nВведите сумму в валюте:")

@bot.message_handler(func=lambda message: True)
def handle_number(message):
    user_id = message.from_user.id
    # bot.send_message(message.chat.id,user_id)
    if user_id in user_data:
        try:
            number = int(message.text)
            option = user_data[user_id]['option']
            del user_data[user_id]  # Remove user data to reset the state
            if option == 'usduzs':
                result = number * float(money()[0])
                bot.send_message(message.chat.id, f"{number}$ = {result:.2f}so'm")
            elif option == 'uzsusd':
                result = number / float(money()[0])
                bot.send_message(message.chat.id, f"{number}so'm = {result:.2f}$")
            elif option == 'rubuzs':
                result = number * float(money()[2])
                bot.send_message(message.chat.id, f"{number}₽ = {result:.2f}so'm")
            elif option == 'uzsrub':
                result = number / float(money()[2])
                bot.send_message(message.chat.id, f"{number}so'm = {result:.2f}₽")
            elif option == 'usdrub':
                result = number * float(money()[0]/money()[2])
                bot.send_message(message.chat.id, f"{number}$ = {result:.2f}₽")
            elif option == 'rubusd':
                result = number / float(money()[0]/money()[2])
                bot.send_message(message.chat.id, f"{number}₽ = {result:.2f}$")
            else:
                bot.send_message(message.chat.id, "Noto'g'ri variant. Iltimos, qayta urinib ko'ring.\nНеверный вариант. Пожалуйста, попробуйте еще раз")
        except ValueError:
            bot.send_message(message.chat.id, ".Yaroqsiz kiritish. Yaroqli raqam kiriting.\nНеверный Ввод. Пожалуйста, введите корректное число.")
    else:
        bot.send_message(message.chat.id, "Iltimos, avval konvertatsiya variantini tanlang.\nСначала выберите вариант преобразования.")

# bot.remove_webhook()
bot.polling()


from __future__ import annotations
import os
import torch
import torch.nn as nn
from lpips import LPIPS
from preloaded_models.resnet import ResNet, BasicBlock

class PerceptualLoss(nn.Module):
    """
    Perceptual loss using features from pretrained deep neural networks trained. The function supports networks
    pretrained on: ImageNet that use the LPIPS approach from Zhang, et al. "The unreasonable effectiveness of deep
    features as a perceptual metric." https://arxiv.org/abs/1801.03924 ; RadImagenet from Mei, et al. "RadImageNet: An
    Open Radiologic Deep Learning Research Dataset for Effective Transfer Learning"
    https://pubs.rsna.org/doi/full/10.1148/ryai.210315 ; and MedicalNet from Chen et al. "Med3D: Transfer Learning for
    3D Medical Image Analysis" https://arxiv.org/abs/1904.00625 .

    The fake 3D implementation is based on a 2.5D approach where we calculate the 2D perceptual on slices from the
    three axis.

    Args:
        spatial_dims: number of spatial dimensions.
        network_type: {``"alex"``, ``"vgg"``, ``"squeeze"``, ``"radimagenet_resnet50"``,
        ``"medicalnet_resnet10_23datasets"``, ``"medicalnet_resnet50_23datasets"``}
            Specifies the network architecture to use. Defaults to ``"alex"``.
        is_fake_3d: if True use 2.5D approach for a 3D perceptual loss.
        fake_3d_ratio: ratio of how many slices per axis are used in the 2.5D approach.
    """

    def __init__(
        self, spatial_dims: int, network_type: str = "alex", is_fake_3d: bool = True, fake_3d_ratio: float = 0.5,
            from_preloaded = False, path_net = None, device = None,
    ):
        super().__init__()
        if device is None:
            self.device = "cuda" if torch.cuda.is_available() else "cpu"
        else:
            self.device = device
        if spatial_dims not in [2, 3]:
            raise NotImplementedError("Perceptual loss is implemented only in 2D and 3D.")

        if (spatial_dims == 2 or is_fake_3d) and "medicalnet_" in network_type:
            raise ValueError(
                "MedicalNet networks are only compatible with ``spatial_dims=3``."
                "Argument is_fake_3d must be set to False."
            )

        self.spatial_dims = spatial_dims
        if spatial_dims == 3 and is_fake_3d is False:
            self.perceptual_function = MedicalNetPerceptualSimilarity(net=network_type, verbose=False,
                                                                      from_preloaded = from_preloaded,
                                                                      path_net = path_net,
                                                                      device = self.device)
        elif "radimagenet_" in network_type:
            self.perceptual_function = RadImageNetPerceptualSimilarity(net=network_type, verbose=False)
        else:
            self.perceptual_function = LPIPS(pretrained=True, net=network_type, verbose=False)
        self.is_fake_3d = is_fake_3d
        self.fake_3d_ratio = fake_3d_ratio

    def _calculate_axis_loss(self, input: torch.Tensor, target: torch.Tensor, spatial_axis: int) -> torch.Tensor:
        """
        Calculate perceptual loss in one of the axis used in the 2.5D approach. After the slices of one spatial axis
        is transformed into different instances in the batch, we compute the loss using the 2D approach.

        Args:
            input: input 5D tensor. BNHWD
            target: target 5D tensor. BNHWD
            spatial_axis: spatial axis to obtain the 2D slices.
        """

        def batchify_axis(x: torch.Tensor, fake_3d_perm: tuple) -> torch.Tensor:
            """
            Transform slices from one spatial axis into different instances in the batch.
            """
            slices = x.float().permute((0,) + fake_3d_perm).contiguous()
            slices = slices.view(-1, x.shape[fake_3d_perm[1]], x.shape[fake_3d_perm[2]], x.shape[fake_3d_perm[3]])

            return slices

        preserved_axes = [2, 3, 4]
        preserved_axes.remove(spatial_axis)

        channel_axis = 1
        input_slices = batchify_axis(x=input, fake_3d_perm=(spatial_axis, channel_axis) + tuple(preserved_axes))
        indices = torch.randperm(input_slices.shape[0])[: int(input_slices.shape[0] * self.fake_3d_ratio)].to(
            input_slices.device
        )
        input_slices = torch.index_select(input_slices, dim=0, index=indices)
        target_slices = batchify_axis(x=target, fake_3d_perm=(spatial_axis, channel_axis) + tuple(preserved_axes))
        target_slices = torch.index_select(target_slices, dim=0, index=indices)

        axis_loss = torch.mean(self.perceptual_function(input_slices, target_slices))

        return axis_loss

    def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        """
        Args:
            input: the shape should be BNHW[D].
            target: the shape should be BNHW[D].
        """
        if target.shape != input.shape:
            raise ValueError(f"ground truth has differing shape ({target.shape}) from input ({input.shape})")

        if self.spatial_dims == 3 and self.is_fake_3d:
            # Compute 2.5D approach
            loss_sagittal = self._calculate_axis_loss(input, target, spatial_axis=2)
            loss_coronal = self._calculate_axis_loss(input, target, spatial_axis=3)
            loss_axial = self._calculate_axis_loss(input, target, spatial_axis=4)
            loss = loss_sagittal + loss_axial + loss_coronal
        else:
            # 2D and real 3D cases
            loss = self.perceptual_function(input, target)

        return torch.mean(loss)

class MedicalNetPerceptualSimilarity(nn.Module):
    """
    Component to perform the perceptual evaluation with the networks pretrained by Chen, et al. "Med3D: Transfer
    Learning for 3D Medical Image Analysis". This class uses torch Hub to download the networks from
    "Warvito/MedicalNet-models".

    Args:
        net: {``"medicalnet_resnet10_23datasets"``, ``"medicalnet_resnet50_23datasets"``}
            Specifies the network architecture to use. Defaults to ``"medicalnet_resnet10_23datasets"``.
        verbose: if false, mute messages from torch Hub load function.
    """

    def __init__(self, net: str = "medicalnet_resnet10_23datasets", verbose: bool = False,
                 from_preloaded=False, path_net = None, device = None) -> None:
        super().__init__()
        if device is None:
            device = "cuda" if torch.cuda.is_available() else "cpu"
        else:
            device = device
        torch.hub._validate_not_a_forked_repo = lambda a, b, c: True
        if from_preloaded:
            self.model = ResNet(BasicBlock, [1, 1, 1, 1])
            pretrained_state_dict = torch.load(path_net)
            pretrained_state_dict = pretrained_state_dict["state_dict"]
            pretrained_state_dict = {k.replace("module.", ""): v for k, v in pretrained_state_dict.items()}
            self.model.load_state_dict(pretrained_state_dict)
        else:
            self.model = torch.hub.load("Warvito/MedicalNet-models", model=net, verbose=verbose, force_reload=False)

        self.model = self.model.to(device)

        self.eval()

    def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        """
        Compute perceptual loss using MedicalNet 3D networks. The input and target tensors are inputted in the
        pre-trained MedicalNet that is used for feature extraction. Then, these extracted features are normalised across
        the channels. Finally, we compute the difference between the input and target features and calculate the mean
        value from the spatial dimensions to obtain the perceptual loss.

        Args:
            input: 3D input tensor with shape BCDHW.
            target: 3D target tensor with shape BCDHW.
        """
        input = medicalnet_intensity_normalisation(input)
        target = medicalnet_intensity_normalisation(target)

        # Get model outputs
        outs_input = self.model.forward(input)
        outs_target = self.model.forward(target)

        # Normalise through the channels
        feats_input = normalize_tensor(outs_input)
        feats_target = normalize_tensor(outs_target)

        results = (feats_input - feats_target) ** 2
        results = spatial_average_3d(results.sum(dim=1, keepdim=True), keepdim=True)

        return results

def spatial_average_3d(x: torch.Tensor, keepdim: bool = True) -> torch.Tensor:
    return x.mean([2, 3, 4], keepdim=keepdim)

def normalize_tensor(x: torch.Tensor, eps: float = 1e-10) -> torch.Tensor:
    norm_factor = torch.sqrt(torch.sum(x**2, dim=1, keepdim=True))
    return x / (norm_factor + eps)

def medicalnet_intensity_normalisation(volume):
    """Based on https://github.com/Tencent/MedicalNet/blob/18c8bb6cd564eb1b964bffef1f4c2283f1ae6e7b/datasets/brains18.py#L133"""
    mean = volume.mean()
    std = volume.std()
    return (volume - mean) / std

class RadImageNetPerceptualSimilarity(nn.Module):
    """
    Component to perform the perceptual evaluation with the networks pretrained on RadImagenet (pretrained by Mei, et
    al. "RadImageNet: An Open Radiologic Deep Learning Research Dataset for Effective Transfer Learning"). This class
    uses torch Hub to download the networks from "Warvito/radimagenet-models".

    Args:
        net: {``"radimagenet_resnet50"``}
            Specifies the network architecture to use. Defaults to ``"radimagenet_resnet50"``.
        verbose: if false, mute messages from torch Hub load function.
    """

    def __init__(self, net: str = "radimagenet_resnet50", verbose: bool = False) -> None:
        super().__init__()
        self.model = torch.hub.load("Warvito/radimagenet-models", model=net, verbose=verbose)
        self.eval()

    def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        """
        We expect that the input is normalised between [0, 1]. Given the preprocessing performed during the training at
        https://github.com/BMEII-AI/RadImageNet, we make sure that the input and target have 3 channels, reorder it from
         'RGB' to 'BGR', and then remove the mean components of each input data channel. The outputs are normalised
        across the channels, and we obtain the mean from the spatial dimensions (similar approach to the lpips package).
        """
        # If input has just 1 channel, repeat channel to have 3 channels
        if input.shape[1] == 1 and target.shape[1] == 1:
            input = input.repeat(1, 3, 1, 1)
            target = target.repeat(1, 3, 1, 1)

        # Change order from 'RGB' to 'BGR'
        input = input[:, [2, 1, 0], ...]
        target = target[:, [2, 1, 0], ...]

        # Subtract mean used during training
        input = subtract_mean(input)
        target = subtract_mean(target)

        # Get model outputs
        outs_input = self.model.forward(input)
        outs_target = self.model.forward(target)

        # Normalise through the channels
        feats_input = normalize_tensor(outs_input)
        feats_target = normalize_tensor(outs_target)

        results = (feats_input - feats_target) ** 2
        results = spatial_average(results.sum(dim=1, keepdim=True), keepdim=True)

        return results

def spatial_average(x: torch.Tensor, keepdim: bool = True) -> torch.Tensor:
    return x.mean([2, 3], keepdim=keepdim)

def subtract_mean(x: torch.Tensor) -> torch.Tensor:
    mean = [0.406, 0.456, 0.485]
    x[:, 0, :, :] -= mean[0]
    x[:, 1, :, :] -= mean[1]
    x[:, 2, :, :] -= mean[2]
    return x


# 0721
# idea: 시뮬레이션, 방향을 설정해주는 것이 핵심. 2차원 리스트를 선언할 때는 컴프리헨션을 이용하는 것이 효율적이다.
# BFS
from collections import deque
import sys

n, m = map(int, sys.stdin.readline().split())
x, y, d = map(int, sys.stdin.readline().split())
arr = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]

visited = [[False] * m for _ in range(n)]

# 상, 하, 좌, 우
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

def bfs(x, y):
    global ans
    q = deque()
    q.append((x, y))
    while q:
        x, y = q.popleft()
        visited[x][y] = True
        ans += 1
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < m and arr[nx][ny] == 0 and not visited[nx][ny]:
                visited[nx][ny] = True
                q.append((nx, ny))

ans = 0
bfs(x, y)
print(ans)

# DFS
import sys

n, m = map(int, sys.stdin.readline().split())
x, y, d = map(int, sys.stdin.readline().split())
arr = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]

visited = [[False] * m for _ in range(n)]

def dfs(x, y):
    global ans
    if 0 <= x < n and 0 <= y < m and arr[x][y] == 0 and not visited[x][y]:
        visited[x][y] = True
        ans += 1
        # 상, 하, 좌, 우
        dfs(x-1, y)
        dfs(x+1, y)
        dfs(x, y-1)
        dfs(x, y+1)

ans = 0
dfs(x, y)
print(ans)

# 구현
import sys
n, m = map(int, sys.stdin.readline().split())
x, y, d = map(int, sys.stdin.readline().split())
arr = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]

visited = [[False] * m for _ in range(n)]

dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

# 왼쪽으로 회전
def turn_left():
    global d
    d -= 1
    if d == -1:
        d = 3

ans = 1
turn_time = 0
visited[x][y] = True
while True:
    turn_left()
    nx = x + dx[d]
    ny = y + dy[d]
    # 회전한 이후 정면에 육지고 가보지 않은 경우
    if arr[nx][ny] == 0 and not visited[nx][ny]:
        visited[nx][ny] = True
        x, y = nx, ny
        turn_time = 0
        ans += 1
    # 회전한 이후 정면에 바다거나 가 본 경우
    else:
        turn_time += 1
    # 네 방향 모두 갈 수 없는 경우
    if turn_time == 4:
        nx = x - dx[d]
        ny = y - dy[d]
        if arr[nx][ny] == 0:
            x, y = nx, ny
        else:
            break
        turn_time = 0

print(ans)

# 회고: BFS/DFS/구현 순으로 만들어보았다. DFS가 가장 간결하지만 BFS가 가장 빠르지만 주어진 방향을 쓰지 않으므로 구현을 쓰는 게 좋을 것 같다.