image
imagewidth (px)
1.28k
4.48k
messages
listlengths
3
3
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from setuptools import find_packages, setup\r\nfrom pip._vendor import tomli\r\n\r\n# For consistent encoding\r\nfrom codecs import open\r\nfrom os import path\r\n\r\n# The directory containing this file\r\nHERE = path.abspath(path.dirname(__file__))\r\n\r\n# Get the long description from the README file\r\nwith open(path.join(HERE, 'README.md'), encoding='utf-8') as f:\r\n LONG_DESCRIPTION = f.read()\r\n\r\nwith open('pyproject.toml', 'r') as f:\r\n VERSION = tomli.load(f)['tool']['commitizen']['version']\r\n\r\nDESCRIPTION = 'A chatbot that enables the user interact with youtube over chat.'\r\n\r\nkey_words = [\r\n 'youtube', 'youtube-api', 'youtube comments', 'youtube videos', 'chat with youtube',\r\n 'youtube channels', 'youtube comment thread', 'create youtube playlist'\r\n]\r\n\r\ninstall_requires = [\r\n 'oryks-youtube',\r\n 'pydantic',\r\n 'pydantic-settings'\r\n]\r\n\r\nsetup(\r\n name='youtube-assistant',\r\n packages=find_packages(\r\n include=[\r\n 'assistant',\r\n ]\r\n ),\r\n version=VERSION,\r\n description=DESCRIPTION,\r\n long_description_content_type='text/markdown'," } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "# $Id: fi.py 9030 2022-03-05 23:28:32Z milde $\r\n# Author: Asko Soukka <[email protected]>\r\n# Copyright: This module has been placed in the public domain.\r\n\r\n# New language mappings are welcome. Before doing a new translation, please\r\n# read <https://docutils.sourceforge.io/docs/howto/i18n.html>.\r\n# Two files must be translated for each language: one in docutils/languages,\r\n# the other in docutils/parsers/rst/languages.\r\n\r\n\"\"\"\r\nFinnish-language mappings for language-dependent features of\r\nreStructuredText.\r\n\"\"\"\r\n\r\n__docformat__ = 'reStructuredText'\r\n\r\n\r\ndirectives = {\r\n # language-dependent: fixed\r\n 'huomio': 'attention',\r\n 'varo': 'caution',\r\n 'code (translation required)': 'code',\r\n 'vaara': 'danger',\r\n 'virhe': 'error',\r\n 'vihje': 'hint',\r\n 't\\u00e4rke\\u00e4\\u00e4': 'important',\r\n 'huomautus': 'note',\r\n 'neuvo': 'tip',\r\n 'varoitus': 'warning',\r\n 'kehotus': 'admonition',\r\n 'sivupalkki': 'sidebar',\r\n 'aihe': 'topic',\r\n 'rivi': 'line-block',\r\n 'tasalevyinen': 'parsed-literal',\r\n 'ohje': 'rubric',\r\n 'epigraafi': 'epigraph',\r\n 'kohokohdat': 'highlights',\r\n 'lainaus': 'pull-quote',\r\n 'taulukko': 'table',\r\n 'csv-taulukko': 'csv-table'," } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .set_config import set_configuration" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from pydantic import BaseModel\r\nfrom datetime import datetime\r\nfrom typing import Optional\r\n\r\n\r\nclass Channel(BaseModel):\r\n channel_id: str\r\n channel_title: str\r\n published_at: datetime\r\n custom_url: str\r\n channel_description: str\r\n channel_thumbnail: str\r\n views_count: int\r\n videos_count: int\r\n subscribers_count: int\r\n \r\nclass Channels(BaseModel):\r\n channels: list[Channel]\r\n \r\nclass GetChannel(BaseModel):\r\n channel_id: str\r\n \r\nclass GetChannels(BaseModel):\r\n offset: Optional[int] = 0\r\n limit: Optional[int] = 10" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from youtube import YouTube\r\nfrom youtube.models import Search\r\nfrom youtube.schemas import (\r\n YouTubeRequest, YouTubeListResponse, YouTubeResponse,\r\n SearchFilter, SearchOptionalParameters, SearchPart\r\n)\r\nfrom typing import Iterator\r\n\r\n\r\nclient_secrets_file = \"/home/lyle/oryks/backend/api/libraries/youtube.json\"\r\ndef get_youtube_client(client_secrets_file: str = client_secrets_file) -> YouTube:\r\n youtube: YouTube = YouTube(client_secret_file=client_secrets_file)\r\n client = youtube.authenticate()\r\n youtube.youtube_client = client\r\n return youtube\r\n\r\nyoutube: YouTube = get_youtube_client(client_secrets_file=\"/home/lyle/Downloads/test.json\")\r\n\r\n\r\n# query: str = ''\r\n# part: SearchPart = SearchPart()\r\n# optional_parameters: SearchOptionalParameters = SearchOptionalParameters(\r\n# q=query,\r\n# type=['video'],\r\n# channelId=\"UCtAcpQcYerN8xxZJYTfWBMw\"\r\n# )\r\n# search_request: YouTubeRequest = YouTubeRequest(\r\n# part=part, \r\n# optional_parameters=optional_parameters\r\n# )\r\n# search_results: YouTubeResponse = youtube.search(search_request)\r\n# search_iterator: Iterator = youtube.get_search_iterator(search_request)\r\n# # res: YouTubeResponse = youtube.find_channel_by_name(display_name=\"Umar Jamil\")\r\n# # print(res.items[0])\r\n# res = next(search_iterator)\r\n# final = []\r\n# for x in search_iterator:\r\n# for search in x:\r\n# final.append(\r\n# dict(" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"\r\nThe Fitbit API breaks from the OAuth2 RFC standard by returning an \"errors\"\r\nobject list, rather than a single \"error\" string. This puts hooks in place so\r\nthat oauthlib can process an error in the results from access token and refresh\r\ntoken responses. This is necessary to prevent getting the generic red herring\r\nMissingTokenError.\r\n\"\"\"\r\n\r\nfrom json import loads, dumps\r\n\r\nfrom oauthlib.common import to_unicode\r\n\r\n\r\ndef fitbit_compliance_fix(session):\r\n def _missing_error(r):\r\n token = loads(r.text)\r\n if \"errors\" in token:\r\n # Set the error to the first one we have\r\n token[\"error\"] = token[\"errors\"][0][\"errorType\"]\r\n r._content = to_unicode(dumps(token)).encode(\"UTF-8\")\r\n return r\r\n\r\n session.register_compliance_hook(\"access_token_response\", _missing_error)\r\n session.register_compliance_hook(\"refresh_token_response\", _missing_error)\r\n return session\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .video import YouTubeVideo" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import operator\r\n\r\n\r\ndef add(a: int | float, b: int | float) -> int | float:\r\n \"\"\"Subtracts two numbers\r\n\r\n Parameters\r\n ----------\r\n a : int or float\r\n The first number to subtract.\r\n b : int or float\r\n The second number to subtract.\r\n\r\n Returns\r\n -------\r\n int or float\r\n The result of subtracting b from a.\"\"\"\r\n return operator.add(a, b)\r\n\r\n\r\ndef subtract(a: int | float, b: int | float) -> int | float:\r\n \"\"\"Subtracts two numbers\r\n\r\n Parameters\r\n ----------\r\n a : int or float\r\n The first number to subtract.\r\n b : int or float\r\n The second number to subtract.\r\n\r\n Returns\r\n -------\r\n int or float\r\n The result of subtracting b from a.\"\"\"\r\n return operator.sub(a, b)\r\n\r\n\r\ndef divide(a: int | float, b: int | float) -> float:\r\n \"\"\"Subtracts two numbers\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import os\r\nfrom dotenv import load_dotenv\r\nfrom rich.prompt import Prompt\r\nfrom src.utils.display import (\r\n display_intro,\r\n select_number_of_posts,\r\n select_topic,\r\n select_search_queries,\r\n)\r\nfrom src.utils.agent import Agent\r\nfrom src.utils.document_loader import RedditSubLoader, TwitterTweetLoader\r\n\r\nload_dotenv()\r\n\r\n\r\ndef main():\r\n display_intro()\r\n topic = select_topic()\r\n platform, keywords, accounts = select_search_queries(topic)\r\n number_of_posts = select_number_of_posts()\r\n\r\n if platform == \"reddit\":\r\n document_loader = RedditSubLoader(\r\n number_submissions=number_of_posts,\r\n keywords=keywords,\r\n subreddits=accounts,\r\n )\r\n elif platform == \"twitter\":\r\n document_loader = TwitterTweetLoader.from_bearer_token(\r\n oauth2_bearer_token=os.environ.get(\"TWITTER_BEARER_TOKEN\"),\r\n number_tweets=number_of_posts,\r\n twitter_users=accounts,\r\n keywords=keywords,\r\n )\r\n else:\r\n raise ValueError(f\"Platform {platform} not supported\")\r\n\r\n agent = Agent(loader=document_loader)\r\n\r\n agent.load_documents()" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from ..resource import YouTubeResource\r\nfrom ...models import (\r\n Video, VideoCategory\r\n)\r\nfrom typing import Any, Optional\r\nfrom ..schemas import (\r\n VideoFilter, VideoOptionalParameters, VideoPart, YouTubeResponse, YouTubeRequest, \r\n YouTubeRatingResponse, ThumbnailSetResponse, VideoReportReasonResponse, LanguageResponse, \r\n RegionResponse, VideoReportAbuse, UploadVideo\r\n)\r\nfrom datetime import datetime\r\nfrom googleapiclient.http import MediaFileUpload\r\nfrom collections import defaultdict\r\n\r\n\r\nclass YouTubeVideo(YouTubeResource):\r\n def __init__(self, youtube_client: Any) -> None:\r\n super().__init__(youtube_client)\r\n \r\n def get_video_ratings(self, video_ids: list[str]) -> YouTubeRatingResponse:\r\n filters: dict = self.generate_filter(self.generate_video_ids, VideoFilter(id=video_ids))\r\n find_video_rating_request: dict = self.youtube_client.videos().getRating(\r\n **filters\r\n )\r\n find_video_rating_result: dict[str, int|str] = find_video_rating_request.execute()\r\n return self.parse_user_video_rating(find_video_rating_result)\r\n \r\n def generate_video_ids(self, video_filter: VideoFilter) -> dict[str, str]:\r\n video_ids: str = ','.join(video_filter.id)\r\n return dict(id=video_ids)\r\n\r\n def find_video_by_id(self, video_id: str) -> Video:\r\n filter: VideoFilter = VideoFilter(id=[video_id])\r\n part: VideoPart = VideoPart()\r\n optional_params: VideoOptionalParameters = VideoOptionalParameters()\r\n request_schema: YouTubeRequest = YouTubeRequest(\r\n part=part, \r\n filter=filter, \r\n optional_parameters=optional_params\r\n )" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from typing import Any\r\n\r\nfrom ...models import (\r\n Channel,\r\n ChannelContentDetails,\r\n ChannelSnippet,\r\n ChannelStatistics,\r\n ChannelStatus,\r\n)\r\nfrom ...schemas import (\r\n ChannelFilter,\r\n ChannelOptionalParameters,\r\n ChannelPart,\r\n YouTubeListResponse,\r\n YouTubeRequest,\r\n)\r\nfrom ..resource import YouTubeResource\r\n\r\n\r\nclass YouTubeChannel(YouTubeResource):\r\n def __init__(self, youtube_client: Any) -> None:\r\n super().__init__(youtube_client)\r\n\r\n def parse_snippet(self, snippet_data: dict[str, Any]) -> ChannelSnippet:\r\n snippet: dict = dict(**self.parse_base_snippet(snippet_data).model_dump())\r\n snippet['custom_url'] = snippet_data['customUrl']\r\n snippet['country'] = snippet_data.get('country', '')\r\n snippet['localized'] = self.parse_localizations(snippet_data['localized'])\r\n return ChannelSnippet(**snippet)\r\n\r\n def parse_content_details(\r\n self, content_details_data: dict\r\n ) -> ChannelContentDetails:\r\n content_details: dict = dict(\r\n **self.parse_base_content_details(content_details_data).model_dump()\r\n )\r\n content_details['related_playlists'] = content_details_data['relatedPlaylists']\r\n return ChannelContentDetails(**content_details)\r\n\r\n def parse_statistics(self, statistics_data: dict) -> ChannelStatistics:" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from json import loads, dumps\r\n\r\nfrom oauthlib.common import to_unicode\r\n\r\n\r\ndef weibo_compliance_fix(session):\r\n def _missing_token_type(r):\r\n token = loads(r.text)\r\n token[\"token_type\"] = \"Bearer\"\r\n r._content = to_unicode(dumps(token)).encode(\"UTF-8\")\r\n return r\r\n\r\n session._client.default_token_placement = \"query\"\r\n session.register_compliance_hook(\"access_token_response\", _missing_token_type)\r\n return session\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"This module declares the application auth models.\"\"\"\r\nfrom flask_dance.consumer.storage.sqla import OAuthConsumerMixin\r\nfrom flask_login import UserMixin\r\n\r\nfrom ...extensions.extensions import db\r\n\r\n\r\nclass User(UserMixin, db.Model):\r\n \"\"\"This class represents a user.\"\"\"\r\n\r\n id = db.Column(db.Integer, primary_key=True)\r\n name = db.Column(db.String(250), unique=True)\r\n email = db.Column(db.String(250), unique=True)\r\n picture = db.Column(db.String(250), unique=True)\r\n\r\n\r\nclass OAuth(OAuthConsumerMixin, db.Model):\r\n \"\"\"This class enables atomatic login.\"\"\"\r\n\r\n user_id = db.Column(db.Integer, db.ForeignKey(User.id))\r\n user = db.relationship(User)\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\r\n\r\nclass ProductionConfig(BaseConfig):\r\n \"\"\"Production configuration.\"\"\"\r\n\r\n TESTING = False\r\n SECRET_KEY = os.environ.get(\"SECRET_KEY\", \"secret-key\")\r\n\r\n\r\nConfig = {\r\n \"development\": DevelopmentConfig,\r\n \"test\": TestingConfig,\r\n \"production\": ProductionConfig,\r\n \"staging\": ProductionConfig,\r\n}\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from database.crud import add_channel\r\nfrom redis import Redis\r\nfrom json import loads\r\nfrom database.database import get_db, create_all\r\nfrom database.models.channel import Channel\r\nfrom datetime import datetime\r\nimport requests\r\nimport sys\r\nimport os\r\nfrom dotenv import load_dotenv\r\nfrom helpers import (\r\n create_es_client, index_resource, get_channel_playlists, get_playlist_videos,\r\n get_video_comments, get_video_comments_task_result, create_comments_data\r\n)\r\nfrom elasticsearch import Elasticsearch\r\n\r\nload_dotenv()\r\n\r\nurl_base = os.environ.get('URL_BASE', 'http://localhost:5000/api/v1/')\r\nredis_host = os.environ.get('REDIS_HOST', 'localhost')\r\nredis = Redis(host=redis_host)\r\n\r\nes_host = os.environ['ES_HOST']\r\nes_port = os.environ['ES_PORT']\r\n\r\nes_client: Elasticsearch = create_es_client(es_host, es_port)\r\nchannels_index = os.environ['CHANNELS_INDEX']\r\nplaylists_index = os.environ['PLAYLISTS_INDEX']\r\nvideos_index = os.environ['VIDEOS_INDEX']\r\n\r\ndef add_channel_to_db():\r\n sub = redis.pubsub()\r\n sub.subscribe('channels')\r\n for data in sub.listen():\r\n if isinstance(data['data'], bytes):\r\n channel_data = loads(data['data'])\r\n channel_data['published_at'] = datetime.utcnow()\r\n channel = Channel(**channel_data)\r\n print(channel)\r\n channel = add_channel(session=get_db, channel=channel)" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from __future__ import annotations\r\n\r\nfrom abc import ABCMeta\r\nfrom collections import OrderedDict\r\nfrom pathlib import Path\r\n\r\nfrom virtualenv.create.describe import PosixSupports, WindowsSupports\r\nfrom virtualenv.create.via_global_ref.builtin.ref import RefMust, RefWhen\r\nfrom virtualenv.create.via_global_ref.builtin.via_global_self_do import ViaGlobalRefVirtualenvBuiltin\r\n\r\n\r\nclass CPython(ViaGlobalRefVirtualenvBuiltin, metaclass=ABCMeta):\r\n @classmethod\r\n def can_describe(cls, interpreter):\r\n return interpreter.implementation == \"CPython\" and super().can_describe(interpreter)\r\n\r\n @classmethod\r\n def exe_stem(cls):\r\n return \"python\"\r\n\r\n\r\nclass CPythonPosix(CPython, PosixSupports, metaclass=ABCMeta):\r\n \"\"\"Create a CPython virtual environment on POSIX platforms.\"\"\"\r\n\r\n @classmethod\r\n def _executables(cls, interpreter):\r\n host_exe = Path(interpreter.system_executable)\r\n major, minor = interpreter.version_info.major, interpreter.version_info.minor\r\n targets = OrderedDict((i, None) for i in [\"python\", f\"python{major}\", f\"python{major}.{minor}\", host_exe.name])\r\n yield host_exe, list(targets.keys()), RefMust.NA, RefWhen.ANY\r\n\r\n\r\nclass CPythonWindows(CPython, WindowsSupports, metaclass=ABCMeta):\r\n @classmethod\r\n def _executables(cls, interpreter):\r\n # symlink of the python executables does not work reliably, copy always instead\r\n # - https://bugs.python.org/issue42013\r\n # - venv\r\n host = cls.host_python(interpreter)\r\n for path in (host.parent / n for n in {\"python.exe\", host.name}): # noqa: PLC0208" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\r\n\r\nclass ProductionConfig(BaseConfig):\r\n \"\"\"Production configuration.\"\"\"\r\n\r\n TESTING = False\r\n SECRET_KEY = os.environ.get(\"SECRET_KEY\", \"secret-key\")\r\n\r\n\r\nConfig = {\r\n \"development\": DevelopmentConfig,\r\n \"test\": TestingConfig,\r\n \"production\": ProductionConfig,\r\n \"staging\": ProductionConfig,\r\n}\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from abc import ABC\r\nfrom ..models import Person\r\nfrom ..nodes import Node\r\n\r\n\r\nclass Command(ABC):\r\n def __init__(self, person: Person, node: Node) -> None:\r\n super().__init__()\r\n self._person: Person = person\r\n self._node: Node = node\r\n\r\n def execute(self, user_input: str) -> bool:\r\n return self._node.execute(user_input=user_input)\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"This module declares the app configuration.\r\n\r\nThe classes include:\r\n\r\nBaseConfig:\r\n Has all the configurations shared by all the environments.\r\n\r\n\"\"\"\r\nimport os\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\n\r\nclass BaseConfig:\r\n \"\"\"Base configuration.\"\"\"\r\n\r\n DEBUG = True\r\n TESTING = False\r\n SECRET_KEY = os.environ.get(\r\n \"SECRET_KEY\", \"df0331cefc6c2b9a5d0208a726a5d1c0fd37324feba25506\"\r\n )\r\n\r\n\r\nclass DevelopmentConfig(BaseConfig):\r\n \"\"\"Development confuguration.\"\"\"\r\n\r\n DEBUG = True\r\n TESTING = False\r\n SECRET_KEY = os.environ.get(\r\n \"SECRET_KEY\", \"df0331cefc6c2b9a5d0208a726a5d1c0fd37324feba25506\"\r\n )\r\n\r\n\r\nclass TestingConfig(BaseConfig):\r\n \"\"\"Testing configuration.\"\"\"\r\n\r\n TESTING = True\r\n SECRET_KEY = os.environ.get(\"SECRET_KEY\", \"secret-key\")" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"Extract the subtitle given youtube URL\"\"\"\r\n\r\nimport io\r\nimport logging\r\nfrom pathlib import Path\r\nfrom typing import Any, Dict, List\r\nfrom injector import singleton, inject\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nfrom bao.settings.settings import Settings\r\n\r\nfrom bao.utils.strings import format_seconds, seconds_to_hh_mm_ss\r\n\r\nimport yaml\r\n\r\nlogger = logging.getLogger()\r\n\r\n\r\n@singleton\r\nclass TranscriptService:\r\n\r\n @inject\r\n def __init__(self, settings: Settings) -> None:\r\n self.settings = settings\r\n\r\n def get_title_pubdate(self, video_url: str) -> tuple:\r\n r = requests.get(video_url)\r\n soup = BeautifulSoup(r.text, features=\"lxml\")\r\n link = soup.find_all(name=\"title\")[0]\r\n title = link.text.strip()\r\n pub_date = soup.find_all(name=\"meta\")[-3][\"content\"][:10]\r\n return title, pub_date.replace(\"-\", \"\")\r\n\r\n def get_transcripts(self, video_url: str, language: str = \"en\"):\r\n try:\r\n from youtube_transcript_api import YouTubeTranscriptApi\r\n except:\r\n logger.exception(\r\n \"cannot import youtube_transcript_api. try 'pip install -U youtube_transcript_api' \"" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"This module hadles user registration, authentication and authorization.\r\n\r\nHas the following methods:\r\nhandle_create_user:\r\ncreate_user:\r\n\"\"\"\r\nfrom flask import flash, redirect, render_template, request, url_for, session\r\nfrom flask_login import login_user\r\n\r\nfrom ...extensions.extensions import bcrypt, db\r\nfrom ..models.user import User\r\nfrom .exceptions import (\r\n EmailAddressExistsException,\r\n EmailDoesNotExistsException,\r\n InvalidEmailAddressFormatException,\r\n InvalidPasswordFormatException,\r\n InvalidToken,\r\n NameExistsException,\r\n NameTooLongException,\r\n NameTooShortException,\r\n PasswordMissmatchException,\r\n PasswordTooShortException,\r\n)\r\nfrom .helpers import (\r\n is_email_address_format_valid,\r\n is_password_valid,\r\n send_confirm_account_email,\r\n send_reset_password_email,\r\n)\r\nfrom werkzeug.datastructures import FileStorage\r\nfrom flask import current_app, jsonify\r\nimport os\r\nimport secrets\r\nfrom ...utils.http_status_codes import HTTP_200_OK\r\n\r\n\r\nALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}\r\n\r\ndef allowed_file(filename: str) -> bool:\r\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"Index entries adapters for sphinx.environment.\"\"\"\r\n\r\nfrom __future__ import annotations\r\n\r\nimport re\r\nimport unicodedata\r\nfrom itertools import groupby\r\nfrom typing import TYPE_CHECKING, Any, Literal\r\n\r\nfrom sphinx.errors import NoUri\r\nfrom sphinx.locale import _, __\r\nfrom sphinx.util import logging\r\nfrom sphinx.util.index_entries import _split_into\r\n\r\nif TYPE_CHECKING:\r\n from sphinx.builders import Builder\r\n from sphinx.environment import BuildEnvironment\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nclass IndexEntries:\r\n def __init__(self, env: BuildEnvironment) -> None:\r\n self.env = env\r\n self.builder: Builder\r\n\r\n def create_index(self, builder: Builder, group_entries: bool = True,\r\n _fixre: re.Pattern = re.compile(r'(.*) ([(][^()]*[)])'),\r\n ) -> list[tuple[str, list[tuple[str, Any]]]]:\r\n \"\"\"Create the real index from the collected index entries.\"\"\"\r\n new: dict[str, list] = {}\r\n\r\n rel_uri: str | Literal[False]\r\n index_domain = self.env.domains['index']\r\n for docname, entries in index_domain.entries.items():\r\n try:\r\n rel_uri = builder.get_relative_uri('genindex', docname)\r\n except NoUri:\r\n rel_uri = False\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from flask.cli import FlaskGroup\r\nfrom app import create_app\r\n\r\n\r\napp = create_app()\r\ncli = FlaskGroup(create_app=create_app)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n cli()" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .video import YouTubeVideo\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from typing import Any, Dict\r\n\r\nfrom injector import inject, singleton\r\nfrom langchain_core.output_parsers.json import JsonOutputParser\r\nfrom langchain_core.prompts import ChatPromptTemplate\r\nfrom langchain_core.runnables import RunnableSerializable\r\n\r\nfrom bao.components.llms import LLMs\r\nfrom bao.settings.settings import Settings\r\n\r\n\r\n@singleton\r\nclass IntentClassification:\r\n @inject\r\n def __init__(self, settings: Settings, llms: LLMs) -> None:\r\n self.settings = settings\r\n self.llms = llms\r\n\r\n def chain(self) -> RunnableSerializable[Dict[str, Any], Dict[str, Any]]:\r\n llm = self.llms.get_llm(\r\n llm_type=self.settings.chain_templates.intent_classify_model\r\n )\r\n chat_template = ChatPromptTemplate.from_messages(\r\n [\r\n (\"system\", self.settings.chain_templates.intent_classify_template),\r\n (\"human\", \"{question}\"),\r\n ]\r\n )\r\n return chat_template | llm | JsonOutputParser()\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .libraries.youtube import YouTube\r\nfrom .config.config import Config\r\n\r\n\r\nclient_secret_file: str = 'client_secret.json'\r\nyoutube: YouTube = YouTube(client_secret_file=client_secret_file)\r\nyoutube.authenticate()" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "# This package will contain the spiders of your Scrapy project\r\n#\r\n# Please refer to the documentation for information on how to create and manage\r\n# your spiders.\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from ...agent import State\r\nfrom ..summary import Summary\r\n\r\n\r\nclass GetAppointment(State):\r\n def execute(self) -> None:\r\n self.agent.ui.get_appointment()\r\n self.agent.transition_to(Summary())\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from dotenv import load_dotenv\r\nload_dotenv()\r\nimport os\r\n\r\nimport googlemaps\r\ngmaps = googlemaps.Client(key=os.environ['GOOGLE_MAPS_API_KEY'])\r\n\r\n# directions_result = gmaps.directions(\r\n# start,\r\n# end,\r\n# waypoints=waypoints,\r\n# mode=transit_type,\r\n# units=\"metric\",\r\n# optimize_waypoints=True,\r\n# traffic_model=\"best_guess\",\r\n# departure_time=start_time,\r\n# )\r\ndef convert_to_coords(input_address):\r\n return gmaps.geocode(input_address)\r\n\r\ngmaps = googlemaps.Client(key=os.environ[\"GOOGLE_MAPS_API_KEY\"])\r\n\r\nexample_coords = convert_to_coords(\"Rachives, Nairobi Kenya\")\r\nprint(example_coords)" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .search import SearchSchema\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"This module declares methods for the login module.\"\"\"\r\nimport sys\r\nimport os\r\nfrom dotenv import load_dotenv\r\nfrom flask import Blueprint, redirect, url_for\r\nfrom flask_dance.consumer import oauth_authorized\r\nfrom flask_dance.consumer.storage.sqla import SQLAlchemyStorage\r\nfrom flask_dance.contrib.google import google, make_google_blueprint\r\nfrom flask_login import current_user, login_required, login_user, logout_user\r\nfrom sqlalchemy.exc import OperationalError\r\nfrom sqlalchemy.orm.exc import NoResultFound\r\n\r\n\r\n# from ..extensions.extensions import db\r\n# from .models.models import OAuth, User\r\n\r\n\r\nauth = Blueprint(\"auth\", __name__)\r\n\r\n\r\ngoogle_blueprint = make_google_blueprint(\r\n client_id=os.environ[\"GOOGLE_OAUTH_CLIENT_ID\"],\r\n client_secret=os.environ[\"GOOGLE_OAUTH_CLIENT_SECRET\"],\r\n scope=[\"profile\", \"email\"]\r\n)\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"\r\nWritten by Joshua Willman\r\nFeatured in \"Modern Pyqt - Create GUI Applications for Project Management, Computer Vision, and Data Analysis\"\r\n\"\"\"\r\n# Import necessary modules\r\nimport sys, os\r\nfrom PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QPushButton, QMessageBox, QMenu, \r\n QFileDialog, QVBoxLayout, QSystemTrayIcon)\r\nfrom PyQt5.QtMultimedia import QAudioRecorder, QAudioEncoderSettings, QMultimedia\r\nfrom PyQt5.QtCore import Qt, QUrl\r\nfrom PyQt5.QtGui import QIcon, QFont\r\nfrom AudioRecorderStyleSheet import style_sheet\r\nimport resources\r\n\r\nclass AudioRecorder(QWidget): \r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.initializeUI()\r\n\r\n def initializeUI(self):\r\n \"\"\"Initialize the window and display its contents to the screen.\"\"\"\r\n self.setFixedSize(360, 540)\r\n self.setWindowTitle('9.1 - Audio Recorder')\r\n\r\n self.audio_path = \"\" # Empty variable for path to audio file\r\n \r\n self.setupWindow()\r\n self.setupSystemTrayIcon()\r\n self.show()\r\n\r\n def setupWindow(self):\r\n \"\"\"Set up widgets in the main window and the QAudioRecorder instance.\"\"\"\r\n # Set up two push buttons (the app's first \"screen\")\r\n self.select_path_button = QPushButton(\"Select Audio Path\")\r\n self.select_path_button.setObjectName(\"SelectFile\")\r\n self.select_path_button.setFixedWidth(140)\r\n self.select_path_button.clicked.connect(self.selectAudioPath)\r\n\r\n self.start_button = QPushButton()" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from typing import Any, Optional\r\n\r\nfrom oryks_google_oauth import GoogleDriveScopes, GoogleOAuth\r\nfrom pydantic import BaseModel\r\n\r\n\r\nclass GoogleDrive(BaseModel):\r\n \"\"\"Provides methods for interacting with the Drive API.\r\n\r\n This class acts as an interface to the Drive API, providing methods for interacting with\r\n the Drive API.\r\n\r\n Attributes\r\n ----------\r\n client_secret_file: str\r\n The path to the json file containing your authentication information.\r\n \"\"\"\r\n\r\n client_secret_file: Optional[str] = None\r\n authenticated: Optional[bool] = False\r\n drive_client: Optional[Any] = None\r\n\r\n def authenticate(self, client_secret_file: Optional[str] = None) -> None:\r\n \"\"\"Authenticate the requests made to drive.\r\n\r\n Used to generate the credentials that are used when authenticating requests to drive.\r\n\r\n Parameters\r\n ----------\r\n client_secret_file: str\r\n The path to clients secret json file from Google\r\n\r\n Raises\r\n ------\r\n ValueError:\r\n When the client secrets file is not provided\r\n FileNotFoundError:\r\n When the secrets file path is not found\r\n \"\"\"\r\n if client_secret_file:" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from langchain_community.document_loaders.generic import GenericLoader\r\nfrom langchain_community.document_loaders.parsers import OpenAIWhisperParser\r\nfrom langchain_community.document_loaders.blob_loaders.youtube_audio import (\r\n YoutubeAudioLoader,\r\n)\r\nfrom langchain_core.documents import Document\r\nfrom os import path\r\n\r\n# Two Karpathy lecture videos\r\nurls = [\"https://www.youtube.com/watch?v=altvPR7x9IA\"]\r\n\r\n# Directory to save audio files\r\ndata_dir = \"data\"\r\nvideo_data_dir = \"video\"\r\ntranscribed_data = \"transcriptions\"\r\nvideo_title = \"sample\"\r\nsave_video_dir = path.join(data_dir, video_data_dir, video_title)\r\nsave_transcript_dir = path.join(data_dir, transcribed_data, video_title + \".txt\")\r\n\r\napi_key: str = \"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\"\r\n\r\nloader = GenericLoader(\r\n YoutubeAudioLoader(urls, save_video_dir), OpenAIWhisperParser(api_key=api_key)\r\n)\r\ndocs = loader.load()\r\n\r\nfull_transcript = \"\"\r\nfor doc in docs:\r\n full_transcript += doc.page_content\r\n\r\nwith open(save_transcript_dir, \"w\", encoding=\"utf-8\") as f:\r\n f.write(full_transcript)\r\n\r\nprint(full_transcript)\r\n\r\n\r\ndef transcribe_video(video_id: str, save_video_dir: str, api_key: str) -> str:\r\n url: str = f\"https://www.youtube.com/watch?v={video_id}\"\r\n loader: GenericLoader = GenericLoader(\r\n YoutubeAudioLoader([url], save_video_dir), OpenAIWhisperParser(api_key=api_key)" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "#!/bin/python3\r\n\r\n# $Id: rst2xetex.py 9115 2022-07-28 17:06:24Z milde $\r\n# Author: Guenter Milde\r\n# Copyright: This module has been placed in the public domain.\r\n\r\n\"\"\"\r\nA minimal front end to the Docutils Publisher, producing Lua/XeLaTeX code.\r\n\"\"\"\r\n\r\ntry:\r\n import locale\r\n locale.setlocale(locale.LC_ALL, '')\r\nexcept Exception:\r\n pass\r\n\r\nfrom docutils.core import publish_cmdline\r\n\r\ndescription = ('Generates LaTeX documents from standalone reStructuredText '\r\n 'sources for compilation with the Unicode-aware TeX variants '\r\n 'XeLaTeX or LuaLaTeX. '\r\n 'Reads from <source> (default is stdin) and writes to '\r\n '<destination> (default is stdout). See '\r\n '<https://docutils.sourceforge.io/docs/user/latex.html> for '\r\n 'the full reference.')\r\n\r\npublish_cmdline(writer_name='xetex', description=description)\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from typing import Any\r\nfrom ..resource import YouTubeResource\r\nfrom ..schemas import (\r\n YouTubeRequest, YouTubeResponse, CommentThreadFilter, CommentThreadOptionalParameters,\r\n CommentThreadPart\r\n)\r\nfrom ...models import CommentThread, Comment\r\nfrom datetime import datetime\r\n\r\n\r\nclass YouTubeCommentThread(YouTubeResource):\r\n def __init__(self, youtube_client: Any) -> None:\r\n super().__init__(youtube_client)\r\n \r\n def generate_optional_parameters(self, optional_params: CommentThreadOptionalParameters) -> dict:\r\n optional: dict = dict()\r\n for key, value in optional_params.model_dump().items():\r\n if value:\r\n optional[key] = value\r\n return optional\r\n \r\n def generate_filter(self, f: CommentThreadFilter) -> dict:\r\n comment_filter: dict = dict()\r\n for key, value in f.model_dump().items():\r\n if value:\r\n comment_filter[key] = value\r\n break\r\n return comment_filter\r\n \r\n def create_request_dict(self, search_schema: YouTubeRequest) -> dict[str, int|str|datetime]:\r\n request_dict: dict[str, int|str|datetime] = dict()\r\n request_dict['part'] = self.generate_part(search_schema.part)\r\n request_dict.update(self.generate_optional_parameters(search_schema.optional_parameters))\r\n request_dict.update(self.generate_filter(search_schema.filter))\r\n return request_dict\r\n \r\n def find_video_comments(self, request: YouTubeRequest) -> YouTubeResponse:\r\n \"\"\"Get a particular video's comments.\"\"\"\r\n comment_thread_req = self.youtube_client.commentThreads().list(\r\n **self.create_request_dict(request)" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "#!/bin/python3\r\n\r\n# $Id: rst2s5.py 9115 2022-07-28 17:06:24Z milde $\r\n# Author: Chris Liechti <[email protected]>\r\n# Copyright: This module has been placed in the public domain.\r\n\r\n\"\"\"\r\nA minimal front end to the Docutils Publisher, producing HTML slides using\r\nthe S5 template system.\r\n\"\"\"\r\n\r\ntry:\r\n import locale\r\n locale.setlocale(locale.LC_ALL, '')\r\nexcept Exception:\r\n pass\r\n\r\nfrom docutils.core import publish_cmdline, default_description\r\n\r\n\r\ndescription = ('Generates S5 (X)HTML slideshow documents from standalone '\r\n 'reStructuredText sources. ' + default_description)\r\n\r\npublish_cmdline(writer_name='s5', description=description)\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from ..resource import YouTubeResource\r\nfrom ...models import Video, Localized, Statistics, Status, VideoCategory\r\nfrom typing import Any, Callable, Optional\r\nfrom ..schemas.video import VideoFilter, VideoOptionalParameters, VideoPart\r\nfrom ..schemas.resource import Filter, RequestSchema, YouTubeResponse\r\nfrom ..schemas.rating import YouTubeRatingResponse\r\nfrom datetime import datetime\r\nfrom googleapiclient.http import MediaFileUpload\r\n\r\n\r\nclass YouTubeVideo(YouTubeResource):\r\n def __init__(self, youtube_client: Any) -> None:\r\n super().__init__(youtube_client)\r\n \r\n def get_video_ratings(self, video_ids: list[str]) -> YouTubeRatingResponse:\r\n filters: dict = self.generate_filter(self.generate_video_ids, VideoFilter(id=video_ids))\r\n find_video_rating_request: dict = self.youtube_client.videos().getRating(\r\n **filters\r\n )\r\n find_video_rating_result: dict[str, int|str] = find_video_rating_request.execute()\r\n return self.parse_user_video_rating(find_video_rating_result)\r\n \r\n def generate_video_ids(self, video_filter: VideoFilter) -> dict[str, str]:\r\n video_ids: str = ','.join(video_filter.id)\r\n return dict(id=video_ids)\r\n\r\n def find_video_by_id(self, video_id: str) -> Video:\r\n return self.find_videos_by_ids(video_id)[0]\r\n\r\n def find_videos_by_ids(self, video_ids: list[str]) -> list[Video]:\r\n filters: dict = self.generate_filter(self.generate_video_ids, VideoFilter(id=[video_ids]))\r\n part: VideoPart = VideoPart()\r\n optional_params: VideoOptionalParameters = VideoOptionalParameters()\r\n request_schema: RequestSchema = RequestSchema(part=part, filter=filters, optional_parameters=optional_params)\r\n request_dict = self.create_request_dict(request_schema)\r\n request_dict.update(filters)\r\n find_video_request: dict = self.youtube_client.videos().list(\r\n **request_dict\r\n )\r\n find_video_result: dict[str, int|str] = find_video_request.execute()" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import torch\r\nimport open_clip\r\nimport cv2\r\nfrom sentence_transformers import util\r\nfrom PIL import Image\r\n\r\n# image processing model\r\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\r\nmodel, _, preprocess = open_clip.create_model_and_transforms('ViT-B-16-plus-240', \r\n pretrained=\"laion400m_e32\")\r\nmodel.to(device)\r\n\r\n\r\ndef imageEncoder(img):\r\n img1 = Image.fromarray(img).convert('RGB')\r\n img1 = preprocess(img1).unsqueeze(0).to(device)\r\n img1 = model.encode_image(img1)\r\n return img1\r\n\r\n\r\ndef generateScore(image1, image2):\r\n test_img = cv2.imread(image1, cv2.IMREAD_UNCHANGED)\r\n data_img = cv2.imread(image2, cv2.IMREAD_UNCHANGED)\r\n img1 = imageEncoder(test_img)\r\n img2 = imageEncoder(data_img)\r\n cos_scores = util.pytorch_cos_sim(img1, img2)\r\n score = round(float(cos_scores[0][0])*100, 2)\r\n return score\r\n\r\n\r\nimage1: str = \"cat.jpeg\"\r\nimage2: str = \"cat2.jpeg\"\r\n\r\nprint(f\"similarity Score: \", round(generateScore(image1, image2), 2))" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from datetime import datetime\r\n\r\nfrom sqlalchemy import ForeignKey\r\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\r\n\r\nfrom ..database import Base\r\n\r\n\r\nclass Post(Base):\r\n __tablename__ = \"posts\"\r\n\r\n id: Mapped[str] = mapped_column(primary_key=True)\r\n author_id: Mapped[str] = mapped_column(ForeignKey(\"users.id\"))\r\n location: Mapped[str]\r\n text: Mapped[str]\r\n image_url: Mapped[str]\r\n date_published: Mapped[datetime] = mapped_column(default_factory=datetime.utcnow)\r\n date_updated: Mapped[datetime] = mapped_column(\r\n onupdate=datetime.utcnow, default_factory=datetime.utcnow\r\n )\r\n\r\n author = relationship(\"User\", back_populates=\"posts\")\r\n bookmarks = relationship(\"Bookmark\", back_populates=\"post\")\r\n likes = relationship(\"Like\", back_populates=\"post\")\r\n comments = relationship(\"Comment\", back_populates=\"post\")\r\n views = relationship(\"View\", back_populates=\"post\")\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from collections import defaultdict\r\nfrom typing import Any\r\n\r\nfrom googleapiclient.http import MediaFileUpload\r\n\r\nfrom ...models import (\r\n BaseContentDetails,\r\n BaseSnippet,\r\n Language,\r\n LanguageSnippet,\r\n Region,\r\n RegionSnippet,\r\n Video,\r\n VideoAbuseReportReason,\r\n VideoAbuseReportReasonSnippet,\r\n VideoCategory,\r\n VideoCategorySnippet,\r\n)\r\nfrom ...schemas import (\r\n UploadVideo,\r\n VideoFilter,\r\n VideoOptionalParameters,\r\n VideoPart,\r\n VideoReportReasonSchema,\r\n YouTubeListResponse,\r\n YouTubeRatingResponse,\r\n YouTubeRequest,\r\n)\r\nfrom ..resource import YouTubeResource\r\n\r\n\r\nclass YouTubeVideo(YouTubeResource):\r\n def __init__(self, youtube_client: Any) -> None:\r\n super().__init__(youtube_client)\r\n\r\n def parse_snippet(self, snippet_data: dict[str, Any]) -> dict[str, Any]:\r\n base_snippet: BaseSnippet = self.parse_base_snippet(snippet_data)\r\n parsed_snippet: dict[str, Any] = base_snippet.model_dump()\r\n parsed_snippet['channel_id'] = snippet_data['channelId']\r\n parsed_snippet['channel_title'] = snippet_data['channelTitle']" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import chainlit as cl\r\nfrom assistant.utils.assistant_utils import welcome_user\r\nfrom assistant.agent import get_agent_executor\r\n\r\n\r\[email protected]_chat_start\r\nasync def start():\r\n res = await cl.AskUserMessage(content=\"What is your name?\", timeout=30).send()\r\n if res:\r\n msg = cl.Message(content=\"\")\r\n await msg.send()\r\n msg.content = welcome_user(user_name=res['content'])\r\n await msg.update()\r\n \r\n\r\[email protected]_message\r\nasync def main(message: cl.Message):\r\n msg = cl.Message(content=\"\")\r\n await msg.send()\r\n query: str = message.content\r\n agent_executor = get_agent_executor(query)\r\n msg.content = agent_executor.invoke({\"input\": query})['output']\r\n await msg.update()" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import cv2\r\nfrom ultralytics import YOLO\r\n\r\n\r\n# model = YOLO(\"yolov9c.pt\")\r\n# model = YOLO(\"yolov8x.pt\")\r\nmodel = YOLO('yolov9c-seg.pt')\r\nres = model.predict(\"soccer.jpeg\", save=True)\r\nprint(res)" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "try:\r\n from urlparse import urlparse, parse_qs\r\nexcept ImportError:\r\n from urllib.parse import urlparse, parse_qs\r\n\r\nfrom oauthlib.common import add_params_to_uri\r\n\r\n\r\ndef instagram_compliance_fix(session):\r\n def _non_compliant_param_name(url, headers, data):\r\n # If the user has already specified the token in the URL\r\n # then there's nothing to do.\r\n # If the specified token is different from ``session.access_token``,\r\n # we assume the user intends to override the access token.\r\n url_query = dict(parse_qs(urlparse(url).query))\r\n token = url_query.get(\"access_token\")\r\n if token:\r\n # Nothing to do, just return.\r\n return url, headers, data\r\n\r\n token = [(\"access_token\", session.access_token)]\r\n url = add_params_to_uri(url, token)\r\n return url, headers, data\r\n\r\n session.register_compliance_hook(\"protected_request\", _non_compliant_param_name)\r\n return session\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"This module declares the app configuration.\r\n\r\nThe classes include:\r\n\r\nBaseConfig:\r\n Has all the configurations shared by all the environments.\r\n\r\n\"\"\"\r\nimport os\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv()\r\n\r\n\r\nclass BaseConfig:\r\n \"\"\"Base configuration.\"\"\"\r\n\r\n DEBUG = True\r\n TESTING = False\r\n SECRET_KEY = os.environ.get(\r\n \"SECRET_KEY\", \"df0331cefc6c2b9a5d0208a726a5d1c0fd37324feba25506\"\r\n )\r\n\r\n\r\nclass DevelopmentConfig(BaseConfig):\r\n \"\"\"Development confuguration.\"\"\"\r\n\r\n DEBUG = True\r\n TESTING = False\r\n SECRET_KEY = os.environ.get(\r\n \"SECRET_KEY\", \"df0331cefc6c2b9a5d0208a726a5d1c0fd37324feba25506\"\r\n )\r\n\r\n\r\nclass TestingConfig(BaseConfig):\r\n \"\"\"Testing configuration.\"\"\"\r\n\r\n TESTING = True\r\n SECRET_KEY = os.environ.get(\"SECRET_KEY\", \"secret-key\")" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"This module declares the extensions used by the application.\"\"\"\r\nfrom flask_bcrypt import Bcrypt\r\nfrom flask_cors import CORS\r\nfrom flask_login import LoginManager\r\nfrom flask_mail import Mail\r\nfrom flask_marshmallow import Marshmallow\r\nfrom flask_migrate import Migrate\r\nfrom flask_sqlalchemy import SQLAlchemy\r\n\r\ncors = CORS()\r\ndb = SQLAlchemy()\r\nmigrate = Migrate()\r\nma = Marshmallow()\r\nbcrypt = Bcrypt()\r\nlogin_manager = LoginManager()\r\nmail = Mail()\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from dataclasses import dataclass\r\nfrom ...extensions.extensions import db\r\nfrom datetime import datetime\r\n\r\n\r\n# @dataclass\r\n# class Friend(db.Model):\r\n# __tablename__ = 'friends'\r\n# id: int = db.Column(db.Integer, primary_key=True)\r\n# user_id: int = db.Column(db.Integer, db.ForeignKey(\"users.id\"))\r\n# friend_id: int = db.Column(db.Integer, db.ForeignKey(\"users.id\"))\r\n# date: datetime = db.Column(db.DateTime, default=datetime.utcnow)\r\n\r\n# user = db.relationship(\"User\", backref=\"friends\")\r\n# friend = db.relationship(\"User\", backref=\"friends\")" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from flask import Flask\r\nfrom .home import code\r\n\r\n\r\ndef register_blueprints(app: Flask) -> bool:\r\n \"\"\"Register the application blueprints.\r\n\r\n Parameters\r\n ----------\r\n app: flask.Flask\r\n A flask app instance\r\n\r\n Returns\r\n -------\r\n bool:\r\n Whether all the blueprints were registered.\r\n \"\"\"\r\n app.register_blueprint(code)\r\n return True" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from typing import List\r\nimport os\r\nfrom functools import lru_cache\r\nimport tweepy\r\nfrom src import logger\r\nfrom src.utils.config import BLACKLIST, SEARCH_FILTERS\r\n\r\nfrom praw import Reddit\r\nfrom praw.models import Subreddit\r\n\r\n\r\n@lru_cache(maxsize=None)\r\ndef get_api():\r\n auth = tweepy.OAuth2BearerHandler(os.environ.get(\"TWITTER_BEARER_TOKEN\"))\r\n api = tweepy.API(auth, parser=tweepy.parsers.JSONParser())\r\n return api\r\n\r\n\r\ndef search_users(q, count):\r\n api = get_api()\r\n users = api.search_users(q=q, count=count)\r\n extracted_users = []\r\n\r\n for user in users:\r\n screen_name = user[\"screen_name\"]\r\n followers_count = user[\"followers_count\"]\r\n statuses_count = user[\"statuses_count\"]\r\n description = user[\"description\"]\r\n profile_url = f\"https://twitter/{screen_name}\"\r\n lang = user[\"lang\"]\r\n\r\n extracted_user = dict(\r\n screen_name=screen_name,\r\n profile_url=profile_url,\r\n description=description,\r\n followers_count=followers_count,\r\n statuses_count=statuses_count,\r\n lang=lang,\r\n )\r\n extracted_users.append(extracted_user)" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import operator\r\n\r\n\r\ndef add(a: int | float, b: int | float) -> int | float:\r\n \"\"\"Subtracts two numbers\r\n\r\n Parameters\r\n ----------\r\n a : int or float\r\n The first number to subtract.\r\n b : int or float\r\n The second number to subtract.\r\n\r\n Returns\r\n -------\r\n int or float\r\n The result of subtracting b from a.\"\"\"\r\n return operator.add(a, b)\r\n\r\n\r\ndef subtract(a: int | float, b: int | float) -> int | float:\r\n \"\"\"Subtracts two numbers\r\n\r\n Parameters\r\n ----------\r\n a : int or float\r\n The first number to subtract.\r\n b : int or float\r\n The second number to subtract.\r\n\r\n Returns\r\n -------\r\n int or float\r\n The result of subtracting b from a.\"\"\"\r\n return operator.sub(a, b)\r\n\r\n\r\ndef divide(a: int | float, b: int | float) -> float:\r\n \"\"\"Subtracts two numbers\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "# This package will contain the spiders of your Scrapy project\r\n#\r\n# Please refer to the documentation for information on how to create and manage\r\n# your spiders.\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .view import home" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from datetime import datetime\r\n\r\nfrom sqlalchemy import ForeignKey\r\nfrom sqlalchemy.orm import Mapped, mapped_column, relationship\r\n\r\nfrom ..database import Base\r\n\r\n\r\nclass View(Base):\r\n __tablename__ = \"views\"\r\n\r\n id: Mapped[str] = mapped_column(primary_key=True)\r\n author_id: Mapped[str] = mapped_column(ForeignKey(\"users.id\"))\r\n post_id: Mapped[str] = mapped_column(ForeignKey(\"posts.id\"))\r\n view_date: Mapped[datetime] = mapped_column(default_factory=datetime.utcnow)\r\n\r\n author = relationship(\"User\", back_populates=\"views\")\r\n post = relationship(\"Post\", back_populates=\"views\")\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from typing import Any, Dict\r\n\r\nfrom injector import inject, singleton\r\nfrom langchain.chains.question_answering import load_qa_chain\r\nfrom langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\r\nfrom langchain_core.runnables import RunnableSerializable\r\n\r\nfrom bao.components.llms import LLMs\r\nfrom bao.settings.settings import Settings\r\n\r\n\r\n@singleton\r\nclass Answering:\r\n @inject\r\n def __init__(self, settings: Settings, llms: LLMs) -> None:\r\n self.settings = settings\r\n self.llms = llms\r\n\r\n def chain(self) -> RunnableSerializable[Dict[str, Any], Dict[str, Any]]:\r\n llm = self.llms.get_llm(llm_type=self.settings.chain_templates.answer_model)\r\n chat_template = ChatPromptTemplate.from_messages(\r\n [\r\n (\"system\", self.settings.chain_templates.answer_template),\r\n MessagesPlaceholder(variable_name=\"chat_history\"),\r\n (\"human\", \"{question}\"),\r\n ]\r\n )\r\n return load_qa_chain(\r\n llm=llm, chain_type=\"stuff\", verbose=True, prompt=chat_template\r\n )\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import ast\r\nfrom ast import ClassDef, FunctionDef, NodeTransformer\r\n\r\nfrom pydantic import BaseModel, Field\r\n\r\nfrom .helpers import (\r\n generate_class_docstring,\r\n generate_function_docstring,\r\n get_class_docstring,\r\n get_class_methods_docstrings,\r\n get_function_docstring,\r\n make_docstring_node,\r\n)\r\n\r\n\r\nclass DocstringWriter(NodeTransformer, BaseModel):\r\n module_code: str = Field(description=\"The modules source code\")\r\n\r\n @property\r\n def module_tree(self):\r\n return ast.parse(self.module_code)\r\n\r\n def visit_ClassDef(self, node):\r\n doc_str: str = ast.get_docstring(node)\r\n for tree_node in self.module_tree.body:\r\n if isinstance(tree_node, ClassDef) and node.name == tree_node.name:\r\n class_code: str = ast.get_source_segment(self.module_code, node)\r\n print(class_code)\r\n class_code_docstring: str = generate_class_docstring(class_code)\r\n class_dcstr = get_class_docstring(class_code_docstring)\r\n new_docstring_node = make_docstring_node(class_dcstr)\r\n if not doc_str:\r\n node.body.insert(0, new_docstring_node)\r\n class_mathods_dcst: dict[str, str] = get_class_methods_docstrings(\r\n class_code_docstring\r\n )\r\n for class_node in node.body:\r\n if isinstance(class_node, FunctionDef):\r\n method_docs: str = class_mathods_dcst[class_node.name]\r\n new_docstring_node = make_docstring_node(method_docs)" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from setuptools import find_packages, setup\r\nfrom pip._vendor import tomli\r\n\r\n# For consistent encoding\r\nfrom codecs import open\r\nfrom os import path\r\n\r\n# The directory containing this file\r\nHERE = path.abspath(path.dirname(__file__))\r\n\r\n# Get the long description from the README file\r\nwith open(path.join(HERE, 'README.md'), encoding='utf-8') as f:\r\n LONG_DESCRIPTION = f.read()\r\n\r\nwith open('pyproject.toml', 'r') as f:\r\n VERSION = tomli.load(f)['tool']['commitizen']['version']\r\n\r\nDESCRIPTION = 'A chatbot that enables the user interact with youtube over chat.'\r\n\r\nkey_words = [\r\n 'youtube', 'youtube-api', 'youtube comments', 'youtube videos', 'chat with youtube',\r\n 'youtube channels', 'youtube comment thread', 'create youtube playlist'\r\n]\r\n\r\ninstall_requires = [\r\n 'oryks-youtube',\r\n 'pydantic',\r\n 'pydantic-settings'\r\n]\r\n\r\nsetup(\r\n name='youtube-assistant',\r\n packages=find_packages(\r\n include=[\r\n 'assistant',\r\n ]\r\n ),\r\n version=VERSION,\r\n description=DESCRIPTION,\r\n long_description_content_type='text/markdown'," } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"This module delares helper methods for the whole app.\r\n\r\nDeclares the following config:\r\n\r\nset_configuration:\r\n For setting the apps configuration.\r\nregister_blueprints:\r\n For registering the application blueprints.\r\nregister_extensions:\r\n For registering the application extensions.\r\n\"\"\"\r\nimport os\r\n\r\nfrom dotenv import load_dotenv\r\nfrom flask import Flask\r\n\r\nfrom ..auth.views import auth\r\nfrom ..config.config import Config\r\nfrom ..exceptions.exceptions import DatabaseNotConnectedException\r\nfrom ..extensions.extensions import bcrypt, cors, db, login_manager, ma, mail, migrate\r\nfrom ..home.views import home\r\nfrom ..post.views import post\r\nfrom ..utils.utils import check_if_database_exists, create_db_conn_string\r\n\r\nload_dotenv()\r\n\r\n\r\ndef set_configuration(app):\r\n \"\"\"Set the application configuration.\r\n\r\n The application configuration will depend on the\r\n environment i.e Test, Development, Staging or Production.\r\n\r\n Parameters\r\n ----------\r\n app: flask.Flask\r\n A flask app instance\r\n\r\n Returns\r\n -------" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "# Streamlit application for New York Housing Market Explorer\r\n\r\n# Required imports\r\nimport streamlit as st\r\nimport pandas as pd\r\nfrom llama_index import SimpleDirectoryReader, ServiceContext, StorageContext, VectorStoreIndex\r\nfrom llama_index.llms import OpenAI\r\nfrom llama_index.embeddings import FastEmbedEmbedding\r\nfrom qdrant_client import QdrantClient\r\nimport json\r\nimport os\r\nfrom sqlalchemy import create_engine\r\nfrom llama_index import SQLDatabase, ServiceContext\r\nfrom llama_index.indices.struct_store import NLSQLTableQueryEngine\r\nfrom pathlib import Path\r\nfrom llama_index.vector_stores.qdrant import QdrantVectorStore\r\nfrom llama_index.query_engine import (\r\n SQLAutoVectorQueryEngine,\r\n RetrieverQueryEngine,\r\n)\r\nfrom llama_index.tools.query_engine import QueryEngineTool\r\nfrom llama_index.indices.vector_store import VectorIndexAutoRetriever\r\n\r\nfrom llama_index.indices.vector_store.retrievers import (\r\n VectorIndexAutoRetriever,\r\n)\r\nfrom llama_index.vector_stores.types import MetadataInfo, VectorStoreInfo\r\nfrom llama_index.query_engine.retriever_query_engine import (\r\n RetrieverQueryEngine,\r\n)\r\nfrom dotenv import load_dotenv\r\nload_dotenv()\r\n\r\n\r\nst.set_page_config(layout=\"wide\")\r\nwrite_dir = Path(\"textdata\")\r\n\r\n# Initialize Qdrant client\r\nclient = QdrantClient(\r\n url=os.environ['QDRANT_URL'], " } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from google_drive import GoogleDrive\r\n\r\n\r\nclient_secrets_file = 'drive.json'\r\ndrive = GoogleDrive(client_secret_file=client_secrets_file)\r\ndrive.authenticate()\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from pydantic_settings import BaseSettings\r\n\r\n\r\nclass BaseConfig(BaseSettings):\r\n max_results: int = 10" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .video import YouTubeVideo\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import torch\r\nimport os\r\nfrom torch import nn\r\nfrom torchvision import transforms\r\nimport numpy as np\r\nimport os\r\nfrom PIL import Image\r\nimport torch\r\nimport os\r\nfrom torch import nn\r\nimport torch.nn.functional as F\r\nimport random\r\n\r\n\r\nclass MaizeNet(nn.Module):\r\n def __init__(self, K) -> None:\r\n super(MaizeNet, self).__init__()\r\n\r\n self.conv_layers = nn.Sequential(\r\n # convolution 1\r\n nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1),\r\n nn.ReLU(),\r\n nn.BatchNorm2d(32),\r\n nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, padding=1),\r\n nn.ReLU(),\r\n nn.BatchNorm2d(32),\r\n nn.MaxPool2d(2),\r\n # Convolution 2\r\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1),\r\n nn.ReLU(),\r\n nn.BatchNorm2d(64),\r\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1),\r\n nn.ReLU(),\r\n nn.BatchNorm2d(64),\r\n nn.MaxPool2d(2),\r\n # Convolution 3\r\n nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=1),\r\n nn.ReLU(),\r\n nn.BatchNorm2d(128),\r\n nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=1)," } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from typing import Any\r\nfrom scrapy import Spider\r\nfrom scrapy.http import Response\r\nfrom scrapy.linkextractors import LinkExtractor \r\n\r\n\r\nclass SlidesLinkExtractor(Spider):\r\n name: str = \"links-extractor\"\r\n \r\n start_urls: list[str] = [\r\n \"https://slidesgo.com/\"\r\n ]\r\n \r\n def __init__(self, name=None, **kwargs): \r\n super().__init__(name, **kwargs) \r\n \r\n self.link_extractor = LinkExtractor(unique=True) \r\n \r\n def parse(self, response: Response, **kwargs: Any) -> Any: \r\n self.logger.info(\"Links spider\")\r\n links = response.css('li.w-1\\/2 a::attr(href)') \r\n \r\n for link in links: \r\n yield {\r\n \"url\": link.get(), \r\n }" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import atexit\r\nimport os\r\nimport sys\r\nimport json\r\nfrom rich.console import Console\r\nfrom langchain.vectorstores import Chroma\r\nfrom langchain.embeddings.openai import OpenAIEmbeddings\r\nimport chromadb\r\nfrom chromadb.config import Settings\r\nimport tiktoken\r\nfrom src import logger\r\nfrom src.utils.chains import (\r\n get_retrieval_qa_chain,\r\n summarize_tweets,\r\n)\r\nfrom src.utils.data_processing import (\r\n get_texts_from_documents,\r\n get_metadatas_from_documents,\r\n)\r\nfrom src.utils.display import display_bot_answer, display_summary_and_questions\r\nfrom src.utils.document_loader import TwitterTweetLoader\r\nfrom src.utils.prompts import summarization_question_template, summarization_template\r\n\r\n\r\nclass TwitterAgent(object):\r\n def __init__(\r\n self,\r\n twitter_users,\r\n keywords,\r\n number_tweets,\r\n persist_db=True,\r\n ):\r\n self.twitter_users = twitter_users\r\n self.keywords = keywords\r\n self.number_tweets = number_tweets\r\n self.loaded_documents = []\r\n self.embeddings = OpenAIEmbeddings()\r\n self.persist_db = persist_db\r\n self.chain = None\r\n self.client = None" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .view import code" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "# Define your item pipelines here\r\n#\r\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\r\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\r\n\r\n\r\n# useful for handling different item types with a single interface\r\nfrom itemadapter import ItemAdapter\r\n\r\n\r\nclass SlidesgoPipeline:\r\n def process_item(self, item, spider):\r\n return item\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"Sphinx environment adapters\"\"\"\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .....libraries.youtube import YouTube" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import logging\r\n\r\nfrom .oauth1_auth import OAuth1\r\nfrom .oauth1_session import OAuth1Session\r\nfrom .oauth2_auth import OAuth2\r\nfrom .oauth2_session import OAuth2Session, TokenUpdated\r\n\r\n__version__ = \"1.3.1\"\r\n\r\nimport requests\r\n\r\nif requests.__version__ < \"2.0.0\":\r\n msg = (\r\n \"You are using requests version %s, which is older than \"\r\n \"requests-oauthlib expects, please upgrade to 2.0.0 or later.\"\r\n )\r\n raise Warning(msg % requests.__version__)\r\n\r\nlogging.getLogger(\"requests_oauthlib\").addHandler(logging.NullHandler())\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import cv2\r\nfrom ultralytics import YOLO\r\n\r\n\r\n# model = YOLO(\"yolov9c.pt\")\r\n# model = YOLO(\"yolov8x.pt\")\r\nmodel = YOLO('yolov9c-seg.pt')\r\nres = model.predict(\"soccer.jpeg\", save=True)\r\nprint(res)" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "SIMPLE_QUERY: list[str] = [\r\n \"\"\"In Jonh Coogans video about 'Being a billionare' find the comment by 'author' and reply to it by disagreeing\"\"\",\r\n \r\n]\r\n\r\nsamples: str = \"\"\"\r\nI do not agree with the comment by Lyle on John Coogans video on 'Billionares'. Craft a reply that \r\nclearly states this, maake it professional.\r\nI want to subscribe/unsubscribe to this channel\r\n\"\"\"" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .resource import Resource\r\nfrom pydantic import Field\r\nfrom datetime import datetime\r\n\r\n\r\nclass Channel(Resource):\r\n \"\"\"This class represnets a youtube channel.\"\"\"\r\n subscribers: int = Field(description='The number of subscribers for this channel.')\r\n date_created: datetime = Field(description='The date and time this channel was created.')" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from dotenv import load_dotenv\r\nload_dotenv()\r\nimport chainlit as cl\r\nfrom farm_agent.agents import agent\r\nfrom farm_agent.utils import load_model, evaluate_image\r\nfrom PIL import Image\r\nimport io\r\n\r\n\r\nuser_location: str = None\r\nuser_name: str = None\r\nwelcome_text: str = \"\"\"\r\nHello there. This is an application that helps farmers monitor the health level of their crops. \r\nStart by giving me your name and location, then upload an image of your crops. I will analyze it to \r\ndetermine the diasease or pest that affects it and then tell you how to deal with the pest or \r\ndisease and where to purchase pesticides or fungicides.\r\n\"\"\"\r\n\r\[email protected]_chat_start\r\nasync def start():\r\n cl.user_session.set(\"agent\", agent)\r\n await cl.Message(content=welcome_text).send()\r\n user_name = await cl.AskUserMessage(content=\"What is your name?\", timeout=120).send()\r\n user_location = await cl.AskUserMessage(content=\"Where are you from?\", timeout=120).send()\r\n res = await cl.AskActionMessage(\r\n content=\"Would you like to determine if your crops are infected by a disease or by pests?\",\r\n actions=[\r\n cl.Action(name=\"Check for diseases\", value=\"diseases\", label=\"✅ Check for diseases\"),\r\n cl.Action(name=\"Check for Pests\", value=\"pests\", label=\"❌ Check for Pests\")\r\n ]\r\n ).send()\r\n if res and res.get(\"value\") == \"diseases\":\r\n files = None\r\n # Wait for the user to upload a file\r\n while files == None:\r\n files = await cl.AskFileMessage(\r\n content=f\"{user_name['content']}, start by uploading an image of your crop.\", \r\n accept=[\"image/jpeg\", \"image/png\", \"image/jpg\"]\r\n ).send()\r\n # Decode the file" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from dotenv import load_dotenv\r\nload_dotenv()\r\nimport chainlit as cl\r\nfrom farm_agent.agents import agent\r\nfrom farm_agent.utils import load_model, evaluate_image\r\nfrom PIL import Image\r\nimport io\r\n\r\n\r\nuser_location: str = None\r\nuser_name: str = None\r\nwelcome_text: str = \"\"\"\r\nHello there. This is an application that helps farmers monitor the health level of their crops. \r\nStart by giving me your name and location, then upload an image of your crops. I will analyze it to \r\ndetermine the diasease or pest that affects it and then tell you how to deal with the pest or \r\ndisease and where to purchase pesticides or fungicides.\r\n\"\"\"\r\n\r\[email protected]_chat_start\r\nasync def start():\r\n cl.user_session.set(\"agent\", agent)\r\n await cl.Message(content=welcome_text).send()\r\n user_name = await cl.AskUserMessage(content=\"What is your name?\", timeout=120).send()\r\n user_location = await cl.AskUserMessage(content=\"Where are you from?\", timeout=120).send()\r\n res = await cl.AskActionMessage(\r\n content=\"Would you like to determine if your crops are infected by a disease or by pests?\",\r\n actions=[\r\n cl.Action(name=\"Check for diseases\", value=\"diseases\", label=\"✅ Check for diseases\"),\r\n cl.Action(name=\"Check for Pests\", value=\"pests\", label=\"❌ Check for Pests\")\r\n ]\r\n ).send()\r\n if res and res.get(\"value\") == \"diseases\":\r\n files = None\r\n # Wait for the user to upload a file\r\n while files == None:\r\n files = await cl.AskFileMessage(\r\n content=f\"{user_name['content']}, start by uploading an image of your crop.\", \r\n accept=[\"image/jpeg\", \"image/png\", \"image/jpg\"]\r\n ).send()\r\n # Decode the file" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "\"\"\"Twitter document loader.\"\"\"\r\nfrom __future__ import annotations\r\nimport os\r\nfrom abc import ABC, abstractmethod\r\nfrom typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union\r\n\r\nfrom praw import Reddit\r\nfrom praw.models import Submission, MoreComments\r\nfrom rich.console import Console\r\nfrom contextlib import nullcontext\r\n\r\nfrom langchain.docstore.document import Document\r\n\r\nfrom src.utils.search import (\r\n search_tweets_by_keywords,\r\n search_tweets_by_usernames,\r\n)\r\n\r\nif TYPE_CHECKING:\r\n import tweepy\r\n from tweepy import OAuth2BearerHandler, OAuthHandler\r\n\r\n\r\ndef _dependable_tweepy_import() -> tweepy:\r\n try:\r\n import tweepy\r\n except ImportError:\r\n raise ValueError(\r\n \"tweepy package not found, please install it with `pip install tweepy`\"\r\n )\r\n return tweepy\r\n\r\n\r\nclass DocumentLoader(ABC):\r\n @property\r\n @abstractmethod\r\n def source(self) -> str:\r\n pass\r\n\r\n @abstractmethod" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from pydantic import BaseModel\r\nfrom datetime import datetime\r\nfrom typing import Optional\r\n\r\n\r\nclass Video(BaseModel):\r\n video_id: str\r\n video_title: str\r\n channel_id: str\r\n published_at: datetime\r\n video_description: str\r\n video_thumbnail: str\r\n views_count: int\r\n likes_count: int\r\n comments_count: int\r\n video_duration: str\r\n \r\nclass Videos(BaseModel):\r\n videos: list[Video]\r\n \r\nclass GetVideo(BaseModel):\r\n video_id: str\r\n \r\nclass GetVideos(BaseModel):\r\n offset: Optional[int] = 0\r\n limit: Optional[int] = 10" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .channel_section import YouTubeChannelSection" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .get_apartment_description import GetApartmentDescription\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import torch\r\nimport clip\r\nfrom PIL import Image\r\n\r\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\r\nmodel, preprocess = clip.load(\"ViT-B/32\", device=device)\r\n\r\nimage = preprocess(Image.open(\"cat.jpeg\")).unsqueeze(0).to(device)\r\nlabels: list[str] = [\"a diagram\", \"a dog\", \"a cat\"]\r\ntext = clip.tokenize(labels).to(device)\r\n\r\nwith torch.no_grad():\r\n image_features = model.encode_image(image)\r\n text_features = model.encode_text(text)\r\n \r\n logits_per_image, logits_per_text = model(image, text)\r\n probs = logits_per_image.softmax(dim=-1).cpu().numpy()\r\n\r\nprint(\"Label probs:\", probs) # prints: [[0.9927937 0.00421068 0.00299572]]\r\nprint(labels[probs.argmax(-1)[0]])\r\n" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "import abc\r\nimport collections\r\nimport collections.abc\r\nimport functools\r\nimport inspect\r\nimport operator\r\nimport sys\r\nimport types as _types\r\nimport typing\r\nimport warnings\r\n\r\n__all__ = [\r\n # Super-special typing primitives.\r\n 'Any',\r\n 'ClassVar',\r\n 'Concatenate',\r\n 'Final',\r\n 'LiteralString',\r\n 'ParamSpec',\r\n 'ParamSpecArgs',\r\n 'ParamSpecKwargs',\r\n 'Self',\r\n 'Type',\r\n 'TypeVar',\r\n 'TypeVarTuple',\r\n 'Unpack',\r\n\r\n # ABCs (from collections.abc).\r\n 'Awaitable',\r\n 'AsyncIterator',\r\n 'AsyncIterable',\r\n 'Coroutine',\r\n 'AsyncGenerator',\r\n 'AsyncContextManager',\r\n 'Buffer',\r\n 'ChainMap',\r\n\r\n # Concrete collection types.\r\n 'ContextManager',\r\n 'Counter'," } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# Copyright (c) 2005-2010 ActiveState Software Inc.\r\n# Copyright (c) 2013 Eddy Petrișor\r\n\r\n\"\"\"Utilities for determining application-specific dirs.\r\n\r\nSee <http://github.com/ActiveState/appdirs> for details and usage.\r\n\"\"\"\r\n# Dev Notes:\r\n# - MSDN on where to store app data files:\r\n# http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120\r\n# - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html\r\n# - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html\r\n\r\n__version__ = \"1.4.4\"\r\n__version_info__ = tuple(int(segment) for segment in __version__.split(\".\"))\r\n\r\n\r\nimport sys\r\nimport os\r\n\r\nPY3 = sys.version_info[0] == 3\r\n\r\nif PY3:\r\n unicode = str\r\n\r\nif sys.platform.startswith('java'):\r\n import platform\r\n os_name = platform.java_ver()[3][0]\r\n if os_name.startswith('Windows'): # \"Windows XP\", \"Windows 7\", etc.\r\n system = 'win32'\r\n elif os_name.startswith('Mac'): # \"Mac OS X\", etc.\r\n system = 'darwin'\r\n else: # \"Linux\", \"SunOS\", \"FreeBSD\", etc.\r\n # Setting this to \"linux2\" is not ideal, but only Windows or Mac\r\n # are actually checked for and the rest of the module expects\r\n # *sys.platform* style strings.\r\n system = 'linux2'\r\nelse:" } ]
[ { "role": "SYSTEM", "content": "You are a helpful assistant that knows how to extract python code from images." }, { "role": "USER", "content": "Extract python code from the given image." }, { "role": "ASSISTANT", "content": "from .channel import Channel" } ]