index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
27,792 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/benchmarks/exercise_runners/exercise_runner_factory.py | 15,17 | 8,18 | create | ExerciseRunnerFactory | 17,18 | 17,18 | class ExerciseRunnerFactory:
RUNNERS = {
"clojure": ClojureExerciseRunner,
"javascript": JavascriptExerciseRunner,
"python": PythonExerciseRunner,
}
@classmethod
def create(cls, language, exercise):
FILL_FUNC_BODY | class ExerciseRunnerFactory:
RUNNERS = {
"clojure": ClojureExerciseRunner,
"javascript": JavascriptExerciseRunner,
"python": PythonExerciseRunner,
}
@classmethod
def create(cls, language, exercise):
FILL_FUNC_BODY | return cls.RUNNERS[language](exercise)
| return cls.RUNNERS[language](exercise)
| 2 | 82 | 16 | 98 | from benchmarks.exercise_runners.clojure_exercise_runner import ClojureExerciseRunner
from benchmarks.exercise_runners.javascript_exercise_runner import (
JavascriptExerciseRunner,
)
from benchmarks.exercise_runners.python_exercise_runner import PythonExerciseRunner
class ExerciseRunnerFactory:
RUNNERS = {
... | from benchmarks.exercise_runners.clojure_exercise_runner import ClojureExerciseRunner
from benchmarks.exercise_runners.javascript_exercise_runner import (
JavascriptExerciseRunner,
)
from benchmarks.exercise_runners.python_exercise_runner import PythonExerciseRunner
class ExerciseRunnerFactory:
RUNNERS = {
... |
27,793 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/benchmarks/exercise_runners/javascript_exercise_runner.py | 21,22 | 7,28 | passed | JavascriptExerciseRunner | 22,28 | 22,28 | class JavascriptExerciseRunner(AbstractExerciseRunner):
def __init__(self, exercise):
super().__init__(exercise, "js")
if not os.path.exists("node_modules"):
subprocess.run(["npm", "install"], stdout=subprocess.PIPE)
self.test_file = self.dir / f"{exercise}.spec.js"
with ... | class JavascriptExerciseRunner(AbstractExerciseRunner):
def __init__(self, exercise):
super().__init__(exercise, "js")
if not os.path.exists("node_modules"):
subprocess.run(["npm", "install"], stdout=subprocess.PIPE)
self.test_file = self.dir / f"{exercise}.spec.js"
with ... | try:
with open(self.test_output_file, "r") as f:
lines = f.readlines()
return "FAIL" not in lines[0] and "PASS" in lines[0]
except FileNotFoundError:
return False
| try:
with open(self.test_output_file, "r") as f:
lines = f.readlines()
return "FAIL" not in lines[0] and "PASS" in lines[0]
except FileNotFoundError:
return False
| 22 | 220 | 71 | 291 | import os
import subprocess
from benchmarks.exercise_runners.abstract_exercise_runner import AbstractExerciseRunner
class JavascriptExerciseRunner(AbstractExerciseRunner):
def __init__(self, exercise):
super().__init__(exercise, "js")
if not os.path.exists("node_modules"):
subprocess.... | import os
import subprocess
from benchmarks.exercise_runners.abstract_exercise_runner import AbstractExerciseRunner
class JavascriptExerciseRunner(AbstractExerciseRunner):
def __init__(self, exercise):
super().__init__(exercise, "js")
if not os.path.exists("node_modules"):
subprocess.... |
27,794 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/benchmarks/exercise_runners/python_exercise_runner.py | 15,16 | 6,22 | passed | PythonExerciseRunner | 16,22 | 16,22 | class PythonExerciseRunner(AbstractExerciseRunner):
def __init__(self, exercise):
super().__init__(exercise, "py")
self.file = Path(str(self.file).replace("-", "_"))
self.full_path = self.dir / self.file
def run_test(self):
self._run_test_command(["pytest", self.dir])
def p... | class PythonExerciseRunner(AbstractExerciseRunner):
def __init__(self, exercise):
super().__init__(exercise, "py")
self.file = Path(str(self.file).replace("-", "_"))
self.full_path = self.dir / self.file
def run_test(self):
self._run_test_command(["pytest", self.dir])
def p... | try:
with open(self.test_output_file, "r") as f:
lines = f.readlines()
return "failed" not in lines[-1] and "passed" in lines[-1]
except FileNotFoundError:
return False
| try:
with open(self.test_output_file, "r") as f:
lines = f.readlines()
return "failed" not in lines[-1] and "passed" in lines[-1]
except FileNotFoundError:
return False
| 22 | 116 | 70 | 186 | from pathlib import Path
from benchmarks.exercise_runners.abstract_exercise_runner import AbstractExerciseRunner
class PythonExerciseRunner(AbstractExerciseRunner):
def __init__(self, exercise):
super().__init__(exercise, "py")
self.file = Path(str(self.file).replace("-", "_"))
self.full_... | from pathlib import Path
from benchmarks.exercise_runners.abstract_exercise_runner import AbstractExerciseRunner
class PythonExerciseRunner(AbstractExerciseRunner):
def __init__(self, exercise):
super().__init__(exercise, "py")
self.file = Path(str(self.file).replace("-", "_"))
self.full_... |
27,796 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/benchmarks/migrations/added_metadata.py | 9,10 | 1,43 | migration | 10,38 | 10,38 | #!/usr/bin/env python
import argparse
from datetime import datetime
from pathlib import Path
from benchmarks.benchmark_run import BenchmarkRun
def migration(path: Path):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("path", type=Path, help="Path to the benchm... | #!/usr/bin/env python
import argparse
from datetime import datetime
from pathlib import Path
from benchmarks.benchmark_run import BenchmarkRun
def migration(path: Path):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("path", type=Path, help="Path to the benchm... | full_result_path = path / "result"
html_path = full_result_path
full_result_path.mkdir(exist_ok=True)
html_path.mkdir(exist_ok=True)
for file in path.iterdir():
if file.is_file() and file.suffix == ".json":
benchmark_run = BenchmarkRun.load_file(file)
try:
... | full_result_path = path / "result"
html_path = full_result_path
full_result_path.mkdir(exist_ok=True)
html_path.mkdir(exist_ok=True)
for file in path.iterdir():
if file.is_file() and file.suffix == ".json":
benchmark_run = BenchmarkRun.load_file(file)
try:
... | 75 | 121 | 413 | 534 | #!/usr/bin/env python
import argparse
from datetime import datetime
from pathlib import Path
from benchmarks.benchmark_run import BenchmarkRun
def migration(path: Path):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("path", type=Path, help="Path to the benchm... | #!/usr/bin/env python
import argparse
from datetime import datetime
from pathlib import Path
from benchmarks.benchmark_run import BenchmarkRun
def migration(path: Path):
FILL_FUNC_BODYif __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("path", type=Path, help="Path to the benchm... | |
27,799 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/broadcast.py | 128,129 | 97,172 | _listener | Broadcast | 129,137 | 129,137 | class Broadcast:
def __init__(self):
self._subscribers: Dict[str, set[Queue[Event | None]]] = {}
self._universal_subscribers: set[Queue[Event | None]] = set()
self._backend = MemoryBackend()
def __enter__(self) -> Broadcast:
self.connect()
return self
def __exit__(s... | class Broadcast:
def __init__(self):
self._subscribers: Dict[str, set[Queue[Event | None]]] = {}
self._universal_subscribers: set[Queue[Event | None]] = set()
self._backend = MemoryBackend()
def __enter__(self) -> Broadcast:
self.connect()
return self
def __exit__(s... | while True:
event = await self._backend.next_published()
for queue in self._subscribers.get(event.channel, set()):
queue.put_nowait(event)
for queue in self._universal_subscribers:
queue.put_nowait(event)
# Since there is no maximum queue ... | while True:
event = await self._backend.next_published()
for queue in self._subscribers.get(event.channel, set()):
queue.put_nowait(event)
for queue in self._universal_subscribers:
queue.put_nowait(event)
# Since there is no maximum queue ... | 33 | 674 | 106 | 780 | # Adapted from https://github.com/encode/broadcaster
from __future__ import annotations
import asyncio
from asyncio import CancelledError, Queue
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, AsyncGenerator, Dict, Iterator, Set
import attr
# TODO: This entire file ... | # Adapted from https://github.com/encode/broadcaster
from __future__ import annotations
import asyncio
from asyncio import CancelledError, Queue
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, AsyncGenerator, Dict, Iterator, Set
import attr
# TODO: This entire file ... |
27,800 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/broadcast.py | 73,74 | 38,93 | publish_async | MemoryBackend | 74,80 | 74,80 | class MemoryBackend:
def __init__(self):
self._subscribed: Set[str] = set()
self._universally_subscribed: bool = False
self._missed_events: defaultdict[str, list[Event]] = defaultdict(list)
def connect(self) -> None:
self._published: Queue[Event] = Queue()
def disconnect(se... | class MemoryBackend:
def __init__(self):
self._subscribed: Set[str] = set()
self._universally_subscribed: bool = False
self._missed_events: defaultdict[str, list[Event]] = defaultdict(list)
def connect(self) -> None:
self._published: Queue[Event] = Queue()
def disconnect(se... | event = Event(channel=channel, message=message)
if channel in self._subscribed or self._universally_subscribed:
await self._published.put(event)
else:
self._missed_events[channel].append(event)
| event = Event(channel=channel, message=message)
if channel in self._subscribed or self._universally_subscribed:
await self._published.put(event)
else:
self._missed_events[channel].append(event)
| 14 | 510 | 71 | 581 | # Adapted from https://github.com/encode/broadcaster
from __future__ import annotations
import asyncio
from asyncio import CancelledError, Queue
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, AsyncGenerator, Dict, Iterator, Set
import attr
# TODO: This entire file ... | # Adapted from https://github.com/encode/broadcaster
from __future__ import annotations
import asyncio
from asyncio import CancelledError, Queue
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, AsyncGenerator, Dict, Iterator, Set
import attr
# TODO: This entire file ... |
27,801 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/broadcast.py | 31,32 | 20,38 | get | Subscriber | 32,38 | 32,38 | class Subscriber:
def __init__(self, queue: Queue[Event | None]) -> None:
self._queue = queue
async def __aiter__(self) -> AsyncGenerator[Event, None]:
try:
while True:
yield await self.get()
except Unsubscribed:
pass
async def get(self) -> E... | class Subscriber:
def __init__(self, queue: Queue[Event | None]) -> None:
self._queue = queue
async def __aiter__(self) -> AsyncGenerator[Event, None]:
try:
while True:
yield await self.get()
except Unsubscribed:
pass
async def get(self) -> E... | item = await self._queue.get()
if item is None:
raise Unsubscribed()
return item
| item = await self._queue.get()
if item is None:
raise Unsubscribed()
return item
| 12 | 106 | 38 | 144 | # Adapted from https://github.com/encode/broadcaster
from __future__ import annotations
import asyncio
from asyncio import CancelledError, Queue
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, AsyncGenerator, Dict, Iterator, Set
import attr
# TODO: This entire file ... | # Adapted from https://github.com/encode/broadcaster
from __future__ import annotations
import asyncio
from asyncio import CancelledError, Queue
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, AsyncGenerator, Dict, Iterator, Set
import attr
# TODO: This entire file ... |
27,802 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/code_feature.py | 71,72 | 1,91 | get_consolidated_feature_refs | 75,91 | 72,91 | from __future__ import annotations
from collections import defaultdict
from pathlib import Path
from typing import Optional
import attr
from ragdaemon.utils import get_document
from mentat.errors import MentatError
from mentat.interval import INTERVAL_FILE_END, Interval
from mentat.session_context import SESSION_CON... | from __future__ import annotations
from collections import defaultdict
from pathlib import Path
from typing import Optional
import attr
from ragdaemon.utils import get_document
from mentat.errors import MentatError
from mentat.interval import INTERVAL_FILE_END, Interval
from mentat.session_context import SESSION_CON... | level_info_by_path = defaultdict[Path, list[Interval | None]](list)
for f in features:
if f.interval.whole_file():
level_info_by_path[f.path].append(None)
else:
level_info_by_path[f.path].append(f.interval)
consolidated_refs = list[str]()
for path, level_info in ... | """
Return a list of 'path:<interval>,<interval>' strings, merging code features with the same path
"""
level_info_by_path = defaultdict[Path, list[Interval | None]](list)
for f in features:
if f.interval.whole_file():
level_info_by_path[f.path].append(None)
else:
... | 57 | 741 | 220 | 961 | from __future__ import annotations
from collections import defaultdict
from pathlib import Path
from typing import Optional
import attr
from ragdaemon.utils import get_document
from mentat.errors import MentatError
from mentat.interval import INTERVAL_FILE_END, Interval
from mentat.session_context import SESSION_CON... | from __future__ import annotations
from collections import defaultdict
from pathlib import Path
from typing import Optional
import attr
from ragdaemon.utils import get_document
from mentat.errors import MentatError
from mentat.interval import INTERVAL_FILE_END, Interval
from mentat.session_context import SESSION_CON... | |
27,803 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/code_feature.py | 44,45 | 18,62 | rel_path | CodeFeature | 45,51 | 45,51 | @attr.define(frozen=True)
class CodeFeature:
"""
Represents a section of the code_message which is included with the prompt.
Includes a section of code and an annotation method.
Attributes:
path: The absolute path to the file.
interval: The lines in the file.
name: The names of ... | @attr.define(frozen=True)
class CodeFeature:
"""
Represents a section of the code_message which is included with the prompt.
Includes a section of code and an annotation method.
Attributes:
path: The absolute path to the file.
interval: The lines in the file.
name: The names of ... | if cwd is not None:
path_string = str(get_relative_path(self.path, cwd))
else:
path_string = str(self.path)
return path_string
| if cwd is not None:
path_string = str(get_relative_path(self.path, cwd))
else:
path_string = str(self.path)
return path_string
| 15 | 419 | 59 | 478 | from __future__ import annotations
from collections import defaultdict
from pathlib import Path
from typing import Optional
import attr
from ragdaemon.utils import get_document
from mentat.errors import MentatError
from mentat.interval import INTERVAL_FILE_END, Interval
from mentat.session_context import SESSION_CON... | from __future__ import annotations
from collections import defaultdict
from pathlib import Path
from typing import Optional
import attr
from ragdaemon.utils import get_document
from mentat.errors import MentatError
from mentat.interval import INTERVAL_FILE_END, Interval
from mentat.session_context import SESSION_CON... |
27,804 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/code_file_manager.py | 59,60 | 20,154 | rename_file | CodeFileManager | 60,70 | 60,70 | class CodeFileManager:
def __init__(self):
self.file_lines = dict[Path, list[str]]()
self.history = EditHistory()
def read_file(self, path: Path) -> list[str]:
# TODO: Change to only ever using this function to read files, then cache files and
# only re-read them when their last... | class CodeFileManager:
def __init__(self):
self.file_lines = dict[Path, list[str]]()
self.history = EditHistory()
def read_file(self, path: Path) -> list[str]:
# TODO: Change to only ever using this function to read files, then cache files and
# only re-read them when their last... | ctx = SESSION_CONTEXT.get()
code_context = ctx.code_context
logging.info(f"Renaming file {abs_path} to {new_abs_path}")
if abs_path in code_context.include_files:
code_context.exclude(abs_path)
os.rename(abs_path, new_abs_path)
if new_abs_path not in code_con... | ctx = SESSION_CONTEXT.get()
code_context = ctx.code_context
logging.info(f"Renaming file {abs_path} to {new_abs_path}")
if abs_path in code_context.include_files:
code_context.exclude(abs_path)
os.rename(abs_path, new_abs_path)
if new_abs_path not in code_con... | 24 | 1,575 | 138 | 1,713 | from __future__ import annotations
import logging
import os
from pathlib import Path
from typing import TYPE_CHECKING, List
from mentat.edit_history import EditHistory
from mentat.errors import MentatError
from mentat.interval import Interval
from mentat.session_context import SESSION_CONTEXT
from mentat.session_inpu... | from __future__ import annotations
import logging
import os
from pathlib import Path
from typing import TYPE_CHECKING, List
from mentat.edit_history import EditHistory
from mentat.errors import MentatError
from mentat.interval import Interval
from mentat.session_context import SESSION_CONTEXT
from mentat.session_inpu... |
27,805 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/command.py | 44,46 | 22,72 | get_command_names | Command | 46,48 | 46,48 | class Command(ABC):
"""
Base Command class. To create a new command, extend this class, provide a command_name,
and import the class in commands.__init__.py so that it is initialized on startup.
"""
# Unfortunately, Command isn't defined here yet, so even with annotations we need quotation marks
... | class Command(ABC):
"""
Base Command class. To create a new command, extend this class, provide a command_name,
and import the class in commands.__init__.py so that it is initialized on startup.
"""
# Unfortunately, Command isn't defined here yet, so even with annotations we need quotation marks
... | return [name for name, command in cls._registered_commands.items() if not command.hidden]
| return [name for name, command in cls._registered_commands.items() if not command.hidden]
| 10 | 432 | 30 | 462 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List, Literal
import attr
from mentat.errors import MentatError
from mentat.session_context import SESSION_CONTEXT
@attr.define
class CommandArgument:
# Required: <arg>, Optional: [arg], Literal: arg
arg_type: Literal... | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List, Literal
import attr
from mentat.errors import MentatError
from mentat.session_context import SESSION_CONTEXT
@attr.define
class CommandArgument:
# Required: <arg>, Optional: [arg], Literal: arg
arg_type: Literal... |
27,806 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/command.py | 76,77 | 72,96 | apply | InvalidCommand | 77,85 | 77,85 | class InvalidCommand(Command, command_name=None):
def __init__(self, invalid_name: str):
self.invalid_name = invalid_name
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @classmethod
def arguments(cls) -> List[CommandArgument]:
raise MentatError("Argument names called on invali... | class InvalidCommand(Command, command_name=None):
def __init__(self, invalid_name: str):
self.invalid_name = invalid_name
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @classmethod
def arguments(cls) -> List[CommandArgument]:
raise MentatError("Argument names called on invali... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
stream.send(
f"{self.invalid_name} is not a valid command. Use /help to see a list of all valid commands",
style="warning",
)
| session_context = SESSION_CONTEXT.get()
stream = session_context.stream
stream.send(
f"{self.invalid_name} is not a valid command. Use /help to see a list of all valid commands",
style="warning",
)
| 25 | 175 | 78 | 253 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List, Literal
import attr
from mentat.errors import MentatError
from mentat.session_context import SESSION_CONTEXT
@attr.define
class CommandArgument:
# Required: <arg>, Optional: [arg], Literal: arg
arg_type: Literal... | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List, Literal
import attr
from mentat.errors import MentatError
from mentat.session_context import SESSION_CONTEXT
@attr.define
class CommandArgument:
# Required: <arg>, Optional: [arg], Literal: arg
arg_type: Literal... |
27,807 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/agent.py | 10,12 | 9,37 | apply | AgentCommand | 12,23 | 12,23 | class AgentCommand(Command, command_name="agent"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argu... | class AgentCommand(Command, command_name="agent"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argu... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
agent_handler = session_context.agent_handler
if agent_handler.agent_enabled:
agent_handler.disable_agent_mode()
stream.send("Agent mode disabled", style="success")
else:
... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
agent_handler = session_context.agent_handler
if agent_handler.agent_enabled:
agent_handler.disable_agent_mode()
stream.send("Agent mode disabled", style="success")
else:
... | 23 | 168 | 119 | 287 | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class AgentCommand(Command, command_name="agent"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
... | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class AgentCommand(Command, command_name="agent"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
... |
27,808 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/amend.py | 10,12 | 9,39 | apply | AmendCommand | 12,21 | 12,21 | class AmendCommand(Command, command_name="amend"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argu... | class AmendCommand(Command, command_name="amend"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argu... | ctx = SESSION_CONTEXT.get()
last_message = ctx.conversation.amend()
if last_message:
ctx.stream.send("Previous response removed from context.", style="info")
ctx.stream.send(last_message, channel="default_prompt")
else:
ctx.stream.send("No previous us... | ctx = SESSION_CONTEXT.get()
last_message = ctx.conversation.amend()
if last_message:
ctx.stream.send("Previous response removed from context.", style="info")
ctx.stream.send(last_message, channel="default_prompt")
else:
ctx.stream.send("No previous us... | 24 | 205 | 107 | 312 | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class AmendCommand(Command, command_name="amend"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
... | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class AmendCommand(Command, command_name="amend"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
... |
27,809 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/clear.py | 10,12 | 9,34 | apply | ClearCommand | 12,20 | 12,20 | class ClearCommand(Command, command_name="clear"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argu... | class ClearCommand(Command, command_name="clear"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argu... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
conversation = session_context.conversation
conversation.clear_messages()
message = "Message history cleared."
stream.send(message, style="success")
| session_context = SESSION_CONTEXT.get()
stream = session_context.stream
conversation = session_context.conversation
conversation.clear_messages()
message = "Message history cleared."
stream.send(message, style="success")
| 17 | 155 | 73 | 228 | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class ClearCommand(Command, command_name="clear"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
... | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class ClearCommand(Command, command_name="clear"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
... |
27,810 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/commit.py | 12,14 | 9,33 | apply | CommitCommand | 14,19 | 14,19 | class CommitCommand(Command, command_name="commit"):
default_message = "Automatic commit"
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [CommandArgument("optional", "commit message")]
@o... | class CommitCommand(Command, command_name="commit"):
default_message = "Automatic commit"
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [CommandArgument("optional", "commit message")]
@o... | if args:
commit(args[0])
else:
commit(self.__class__.default_message)
| if args:
commit(args[0])
else:
commit(self.__class__.default_message)
| 5 | 183 | 36 | 219 | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.git_handler import commit
class CommitCommand(Command, command_name="commit"):
default_message = "Automatic commit"
@override
async def apply(self, *args: str) -> None:... | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.git_handler import commit
class CommitCommand(Command, command_name="commit"):
default_message = "Automatic commit"
@override
async def apply(self, *args: str) -> None:... |
27,811 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/config.py | 11,13 | 10,75 | apply | ConfigCommand | 13,45 | 13,45 | class ConfigCommand(Command, command_name="config"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [
CommandArgument("required", "setting"),
CommandArgument("optional", "va... | class ConfigCommand(Command, command_name="config"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [
CommandArgument("required", "setting"),
CommandArgument("optional", "va... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
config = session_context.config
if len(args) == 0:
stream.send("No config option specified", style="warning")
else:
setting = args[0]
if hasattr(config, setting):
... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
config = session_context.config
if len(args) == 0:
stream.send("No config option specified", style="warning")
else:
setting = args[0]
if hasattr(config, setting):
... | 95 | 285 | 398 | 683 | from typing import List
import attr
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class ConfigCommand(Command, command_name="config"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY ... | from typing import List
import attr
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class ConfigCommand(Command, command_name="config"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY ... |
27,812 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/exclude.py | 33,36 | 12,53 | argument_autocompletions | ExcludeCommand | 36,49 | 36,49 | class ExcludeCommand(Command, command_name="exclude"):
@override
async def apply(self, *args: str) -> None:
session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_context = session_context.code_context
if len(args) == 0:
stream.send("No files sp... | class ExcludeCommand(Command, command_name="exclude"):
@override
async def apply(self, *args: str) -> None:
session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_context = session_context.code_context
if len(args) == 0:
stream.send("No files sp... | ctx = SESSION_CONTEXT.get()
file_names = get_command_filename_completions(arguments[-1])
filtered_file_names: List[str] = []
for file_name in file_names:
file_path = Path(file_name).expanduser().resolve()
for included_file in ctx.code_context.include_files.keys()... | ctx = SESSION_CONTEXT.get()
file_names = get_command_filename_completions(arguments[-1])
filtered_file_names: List[str] = []
for file_name in file_names:
file_path = Path(file_name).expanduser().resolve()
for included_file in ctx.code_context.include_files.keys()... | 27 | 317 | 151 | 468 | from pathlib import Path
from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
from mentat.utils import get_relative_path
class E... | from pathlib import Path
from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
from mentat.utils import get_relative_path
class E... |
27,813 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/include.py | 12,14 | 11,41 | apply | IncludeCommand | 14,27 | 14,27 | class IncludeCommand(Command, command_name="include"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [CommandArgument("required", ["path", "glob pattern"], repeatable=True)]
@override
@cl... | class IncludeCommand(Command, command_name="include"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [CommandArgument("required", ["path", "glob pattern"], repeatable=True)]
@override
@cl... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_context = session_context.code_context
if len(args) == 0:
stream.send("No files specified", style="warning")
return
for file_path in args:
included_paths = code_conte... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_context = session_context.code_context
if len(args) == 0:
stream.send("No files specified", style="warning")
return
for file_path in args:
included_paths = code_conte... | 38 | 185 | 161 | 346 | from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
from mentat.utils import get_relative_path
class IncludeCommand(Command, co... | from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
from mentat.utils import get_relative_path
class IncludeCommand(Command, co... |
27,814 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/load.py | 15,17 | 14,64 | apply | LoadCommand | 17,50 | 17,50 | class LoadCommand(Command, command_name="load"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [CommandArgument("optional", ["path"])]
@override
@classmethod
def argument_autocompleti... | class LoadCommand(Command, command_name="load"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [CommandArgument("optional", ["path"])]
@override
@classmethod
def argument_autocompleti... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_context = session_context.code_context
context_file_path = mentat_dir_path / "context.json"
if len(args) > 1:
stream.send("Only one context file can be loaded at a time", style="warning")
... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_context = session_context.code_context
context_file_path = mentat_dir_path / "context.json"
if len(args) > 1:
stream.send("Only one context file can be loaded at a time", style="warning")
... | 92 | 192 | 368 | 560 | import json
from pathlib import Path
from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.errors import PathValidationError
from mentat.session_context import SESSION_CO... | import json
from pathlib import Path
from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.errors import PathValidationError
from mentat.session_context import SESSION_CO... |
27,815 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/redo.py | 10,12 | 9,35 | apply | RedoCommand | 12,21 | 12,21 | class RedoCommand(Command, command_name="redo"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argume... | class RedoCommand(Command, command_name="redo"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argume... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_file_manager = session_context.code_file_manager
errors = await code_file_manager.history.redo()
if errors:
stream.send("\n".join(errors), style="error")
stream.send("Redo complete",... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_file_manager = session_context.code_file_manager
errors = await code_file_manager.history.redo()
if errors:
stream.send("\n".join(errors), style="error")
stream.send("Redo complete",... | 20 | 164 | 104 | 268 | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class RedoCommand(Command, command_name="redo"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
... | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class RedoCommand(Command, command_name="redo"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
... |
27,816 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/run.py | 11,13 | 10,38 | apply | RunCommand | 13,21 | 13,21 | class RunCommand(Command, command_name="run"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [
CommandArgument("required", "command"),
CommandArgument("optional", "args", r... | class RunCommand(Command, command_name="run"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [
CommandArgument("required", "command"),
CommandArgument("optional", "args", r... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
conversation = session_context.conversation
if not args:
stream.send("No command given", style="failure")
return
await conversation.run_command(list(args))
| session_context = SESSION_CONTEXT.get()
stream = session_context.stream
conversation = session_context.conversation
if not args:
stream.send("No command given", style="failure")
return
await conversation.run_command(list(args))
| 19 | 201 | 80 | 281 | from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class RunCommand(Command, command_name="run"):
@override
async def ... | from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class RunCommand(Command, command_name="run"):
@override
async def ... |
27,817 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/sample.py | 44,46 | 12,47 | help_message | SampleCommand | 46,47 | 46,47 | class SampleCommand(Command, command_name="sample"):
hidden = True # Waiting for parse_message to be complete
async def apply(self, *args: str) -> None:
session_context = SESSION_CONTEXT.get()
sampler = session_context.sampler
stream = session_context.stream
try:
sa... | class SampleCommand(Command, command_name="sample"):
hidden = True # Waiting for parse_message to be complete
async def apply(self, *args: str) -> None:
session_context = SESSION_CONTEXT.get()
sampler = session_context.sampler
stream = session_context.stream
try:
sa... | return "Save a sample of the current session."
| return "Save a sample of the current session."
| 8 | 368 | 13 | 381 | from pathlib import Path
from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.errors import SampleError
from mentat.session_context import SESSION_CONTEXT
from mentat.utils import mentat_dir_path
class SampleCommand(Command, command_n... | from pathlib import Path
from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.errors import SampleError
from mentat.session_context import SESSION_CONTEXT
from mentat.utils import mentat_dir_path
class SampleCommand(Command, command_n... |
27,818 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/save.py | 15,17 | 14,53 | apply | SaveCommand | 17,39 | 17,39 | class SaveCommand(Command, command_name="save"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [CommandArgument("optional", ["path"])]
@override
@classmethod
def argument_autocompleti... | class SaveCommand(Command, command_name="save"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [CommandArgument("optional", ["path"])]
@override
@classmethod
def argument_autocompleti... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_context = session_context.code_context
context_file_path = mentat_dir_path / "context.json"
if len(args) > 1:
stream.send("Only one context file can be saved at a time", style="warning")
... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_context = session_context.code_context
context_file_path = mentat_dir_path / "context.json"
if len(args) > 1:
stream.send("Only one context file can be saved at a time", style="warning")
... | 65 | 181 | 259 | 440 | import json
from pathlib import Path
from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.errors import PathValidationError
from mentat.session_context import SESSION_CO... | import json
from pathlib import Path
from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.errors import PathValidationError
from mentat.session_context import SESSION_CO... |
27,819 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/screenshot.py | 12,14 | 11,63 | apply | ScreenshotCommand | 14,49 | 14,49 | class ScreenshotCommand(Command, command_name="screenshot"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [CommandArgument("optional", ["path", "url"])]
@override
@classmethod
def ar... | class ScreenshotCommand(Command, command_name="screenshot"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return [CommandArgument("optional", ["path", "url"])]
@override
@classmethod
def ar... | session_context = SESSION_CONTEXT.get()
vision_manager = session_context.vision_manager
stream = session_context.stream
config = session_context.config
conversation = session_context.conversation
model = config.model
if "gpt" in model:
if not ("vision... | session_context = SESSION_CONTEXT.get()
vision_manager = session_context.vision_manager
stream = session_context.stream
config = session_context.config
conversation = session_context.conversation
model = config.model
if "gpt" in model:
if not ("vision... | 108 | 194 | 369 | 563 | from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
from mentat.vision.vision_manager import ScreenshotException
class Screensh... | from typing import List
from typing_extensions import override
from mentat.auto_completer import get_command_filename_completions
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
from mentat.vision.vision_manager import ScreenshotException
class Screensh... |
27,820 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/talk.py | 42,43 | 26,59 | record | Recorder | 43,59 | 43,59 | class Recorder:
def __init__(self):
self.shutdown = Event()
(logs_path / "audio").mkdir(parents=True, exist_ok=True)
self.file = logs_path / "audio/talk_transcription.wav"
def callback(
self,
in_data: np.ndarray[Any, Any],
frames: int,
time: Any,
... | class Recorder:
def __init__(self):
self.shutdown = Event()
(logs_path / "audio").mkdir(parents=True, exist_ok=True)
self.file = logs_path / "audio/talk_transcription.wav"
def callback(
self,
in_data: np.ndarray[Any, Any],
frames: int,
time: Any,
... | self.start_time = default_timer()
self.q: queue.Queue[np.ndarray[Any, Any]] = queue.Queue()
with sf.SoundFile( # pyright: ignore[reportPossiblyUnboundVariable]
self.file, mode="w", samplerate=RATE, channels=1
) as file:
with sd.InputStream( # pyright: ignore[re... | self.start_time = default_timer()
self.q: queue.Queue[np.ndarray[Any, Any]] = queue.Queue()
with sf.SoundFile( # pyright: ignore[reportPossiblyUnboundVariable]
self.file, mode="w", samplerate=RATE, channels=1
) as file:
with sd.InputStream( # pyright: ignore[re... | 43 | 149 | 211 | 360 | import asyncio
import queue
from asyncio import Event
from timeit import default_timer
from typing import Any, List
import numpy as np
from typing_extensions import override
try:
import sounddevice as sd
import soundfile as sf
audio_available = True
except Exception:
audio_available = False
from me... | import asyncio
import queue
from asyncio import Event
from timeit import default_timer
from typing import Any, List
import numpy as np
from typing_extensions import override
try:
import sounddevice as sd
import soundfile as sf
audio_available = True
except Exception:
audio_available = False
from me... |
27,821 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/talk.py | 60,62 | 59,100 | apply | TalkCommand | 62,86 | 62,86 | class TalkCommand(Command, command_name="talk"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argume... | class TalkCommand(Command, command_name="talk"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argume... | ctx = SESSION_CONTEXT.get()
if not audio_available:
# sounddevice manages port audio on Mac and Windows so we print an apt specific message
ctx.stream.send(
"Audio is not available on this system. You probably need to install"
" PortAudio. For exam... | ctx = SESSION_CONTEXT.get()
if not audio_available:
# sounddevice manages port audio on Mac and Windows so we print an apt specific message
ctx.stream.send(
"Audio is not available on this system. You probably need to install"
" PortAudio. For exam... | 108 | 154 | 350 | 504 | import asyncio
import queue
from asyncio import Event
from timeit import default_timer
from typing import Any, List
import numpy as np
from typing_extensions import override
try:
import sounddevice as sd
import soundfile as sf
audio_available = True
except Exception:
audio_available = False
from me... | import asyncio
import queue
from asyncio import Event
from timeit import default_timer
from typing import Any, List
import numpy as np
from typing_extensions import override
try:
import sounddevice as sd
import soundfile as sf
audio_available = True
except Exception:
audio_available = False
from me... |
27,822 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/undo.py | 10,12 | 9,35 | apply | UndoCommand | 12,21 | 12,21 | class UndoCommand(Command, command_name="undo"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argume... | class UndoCommand(Command, command_name="undo"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], argume... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_file_manager = session_context.code_file_manager
errors = code_file_manager.history.undo()
if errors:
stream.send("\n".join(errors), style="error")
stream.send("Undo complete", style... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_file_manager = session_context.code_file_manager
errors = code_file_manager.history.undo()
if errors:
stream.send("\n".join(errors), style="error")
stream.send("Undo complete", style... | 19 | 162 | 103 | 265 | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class UndoCommand(Command, command_name="undo"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
... | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class UndoCommand(Command, command_name="undo"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
... |
27,823 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/undoall.py | 10,12 | 9,35 | apply | UndoAllCommand | 12,21 | 12,21 | class UndoAllCommand(Command, command_name="undo-all"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str],... | class UndoAllCommand(Command, command_name="undo-all"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str],... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_file_manager = session_context.code_file_manager
errors = code_file_manager.history.undo_all()
if errors:
stream.send("\n".join(errors), style="error")
stream.send("Undos complete", ... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
code_file_manager = session_context.code_file_manager
errors = code_file_manager.history.undo_all()
if errors:
stream.send("\n".join(errors), style="error")
stream.send("Undos complete", ... | 19 | 164 | 105 | 269 | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class UndoAllCommand(Command, command_name="undo-all"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @overri... | from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
class UndoAllCommand(Command, command_name="undo-all"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @overri... |
27,824 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/command/commands/viewer.py | 13,15 | 12,37 | apply | ViewerCommand | 15,23 | 15,23 | class ViewerCommand(Command, command_name="viewer"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], ar... | class ViewerCommand(Command, command_name="viewer"):
@override
async def apply(self, *args: str) -> None:
FILL_FUNC_BODY @override
@classmethod
def arguments(cls) -> List[CommandArgument]:
return []
@override
@classmethod
def argument_autocompletions(cls, arguments: list[str], ar... | session_context = SESSION_CONTEXT.get()
conversation = session_context.conversation
logs = get_transcript_logs()
viewer_path = create_viewer([Transcript(id="Current", messages=conversation.literal_messages)] + logs)
webbrowser.open(f"file://{viewer_path.resolve()}")
| session_context = SESSION_CONTEXT.get()
conversation = session_context.conversation
logs = get_transcript_logs()
viewer_path = create_viewer([Transcript(id="Current", messages=conversation.literal_messages)] + logs)
webbrowser.open(f"file://{viewer_path.resolve()}")
| 16 | 161 | 101 | 262 | import webbrowser
from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
from mentat.transcripts import Transcript, get_transcript_logs
from mentat.utils import create_viewer
class ViewerCommand(Co... | import webbrowser
from typing import List
from typing_extensions import override
from mentat.command.command import Command, CommandArgument
from mentat.session_context import SESSION_CONTEXT
from mentat.transcripts import Transcript, get_transcript_logs
from mentat.utils import create_viewer
class ViewerCommand(Co... |
27,825 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/daemon.py | 150,151 | 1,159 | main | 151,159 | 151,159 | import ast
import re
from pathlib import Path
from textwrap import dedent
from typing import List, Optional, Tuple
import openai
from watchfiles import Change, watch
openai_client = openai.Client()
def get_mentat_comment(filename: Path) -> Optional[Tuple[int, str]]:
with open(filename, "r") as file:
for... | import ast
import re
from pathlib import Path
from textwrap import dedent
from typing import List, Optional, Tuple
import openai
from watchfiles import Change, watch
openai_client = openai.Client()
def get_mentat_comment(filename: Path) -> Optional[Tuple[int, str]]:
with open(filename, "r") as file:
for... | print(f"Watching {path}")
for changes in watch(path, force_polling=True):
for change_type, _change_path in changes:
change_path = Path(_change_path)
if change_path.is_file() is False:
continue
if change_type == Change.modified:
process_... | print(f"Watching {path}")
for changes in watch(path, force_polling=True):
for change_type, _change_path in changes:
change_path = Path(_change_path)
if change_path.is_file() is False:
continue
if change_type == Change.modified:
process_... | 25 | 1,301 | 103 | 1,404 | import ast
import re
from pathlib import Path
from textwrap import dedent
from typing import List, Optional, Tuple
import openai
from watchfiles import Change, watch
openai_client = openai.Client()
def get_mentat_comment(filename: Path) -> Optional[Tuple[int, str]]:
with open(filename, "r") as file:
for... | import ast
import re
from pathlib import Path
from textwrap import dedent
from typing import List, Optional, Tuple
import openai
from watchfiles import Change, watch
openai_client = openai.Client()
def get_mentat_comment(filename: Path) -> Optional[Tuple[int, str]]:
with open(filename, "r") as file:
for... | |
27,826 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/diff_context.py | 136,137 | 1,158 | _get_treeish_type | 137,158 | 137,158 | import subprocess
from pathlib import Path
from typing import List, Literal, Optional
from mentat.git_handler import (
check_head_exists,
get_diff_for_file,
get_files_in_diff,
get_git_root_for_path,
get_treeish_metadata,
get_untracked_files,
)
from mentat.session_context import SESSION_CONTEXT
... | import subprocess
from pathlib import Path
from typing import List, Literal, Optional
from mentat.git_handler import (
check_head_exists,
get_diff_for_file,
get_files_in_diff,
get_git_root_for_path,
get_treeish_metadata,
get_untracked_files,
)
from mentat.session_context import SESSION_CONTEXT
... | if " " in treeish:
parts = treeish.split(" ")
types = [_get_treeish_type(git_root, part) for part in parts]
if not all(types):
return None
return "compare"
object_type = _git_command(git_root, "cat-file", "-t", treeish)
if not object_type:
return None
... | if " " in treeish:
parts = treeish.split(" ")
types = [_get_treeish_type(git_root, part) for part in parts]
if not all(types):
return None
return "compare"
object_type = _git_command(git_root, "cat-file", "-t", treeish)
if not object_type:
return None
... | 61 | 1,371 | 201 | 1,572 | import subprocess
from pathlib import Path
from typing import List, Literal, Optional
from mentat.git_handler import (
check_head_exists,
get_diff_for_file,
get_files_in_diff,
get_git_root_for_path,
get_treeish_metadata,
get_untracked_files,
)
from mentat.session_context import SESSION_CONTEXT
... | import subprocess
from pathlib import Path
from typing import List, Literal, Optional
from mentat.git_handler import (
check_head_exists,
get_diff_for_file,
get_files_in_diff,
get_git_root_for_path,
get_treeish_metadata,
get_untracked_files,
)
from mentat.session_context import SESSION_CONTEXT
... | |
27,827 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/diff_context.py | 69,70 | 17,126 | _get_treeish_metadata | DiffContext | 70,73 | 70,73 | class DiffContext:
target: str = ""
name: str = "index (last commit)"
def __init__(
self,
stream: SessionStream,
cwd: Path,
diff: Optional[str] = None,
pr_diff: Optional[str] = None,
):
self.git_root = get_git_root_for_path(cwd, raise_error=False)
... | class DiffContext:
target: str = ""
name: str = "index (last commit)"
def __init__(
self,
stream: SessionStream,
cwd: Path,
diff: Optional[str] = None,
pr_diff: Optional[str] = None,
):
self.git_root = get_git_root_for_path(cwd, raise_error=False)
... | meta = get_treeish_metadata(git_root, _target)
return f'{meta["hexsha"][:8]}: {meta["summary"]}'
| meta = get_treeish_metadata(git_root, _target)
return f'{meta["hexsha"][:8]}: {meta["summary"]}'
| 7 | 1,076 | 44 | 1,120 | import subprocess
from pathlib import Path
from typing import List, Literal, Optional
from mentat.git_handler import (
check_head_exists,
get_diff_for_file,
get_files_in_diff,
get_git_root_for_path,
get_treeish_metadata,
get_untracked_files,
)
from mentat.session_context import SESSION_CONTEXT
... | import subprocess
from pathlib import Path
from typing import List, Literal, Optional
from mentat.git_handler import (
check_head_exists,
get_diff_for_file,
get_files_in_diff,
get_git_root_for_path,
get_treeish_metadata,
get_untracked_files,
)
from mentat.session_context import SESSION_CONTEXT
... |
27,828 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/edit_history.py | 56,57 | 9,66 | undo_all | EditHistory | 57,66 | 57,66 | class EditHistory:
def __init__(self):
self.edits = list[list[FileEdit]]()
self.cur_edits = list[FileEdit]()
self.undone_edits = list[list[FileEdit]]()
def add_edit(self, file_edit: FileEdit):
self.cur_edits.append(file_edit)
def push_edits(self):
if self.cur_edits:... | class EditHistory:
def __init__(self):
self.edits = list[list[FileEdit]]()
self.cur_edits = list[FileEdit]()
self.undone_edits = list[list[FileEdit]]()
def add_edit(self, file_edit: FileEdit):
self.cur_edits.append(file_edit)
def push_edits(self):
if self.cur_edits:... | if not self.edits:
return ["No edits available to undo"]
errors = list[str]()
while self.edits:
error = self.undo()
if error:
errors += error
return errors
| if not self.edits:
return ["No edits available to undo"]
errors = list[str]()
while self.edits:
error = self.undo()
if error:
errors += error
return errors
| 24 | 524 | 70 | 594 | from typing import List
from mentat.errors import HistoryError
from mentat.parsers.file_edit import FileEdit
from mentat.session_context import SESSION_CONTEXT
# TODO: Keep track of when we create directories so we can undo those as well
class EditHistory:
def __init__(self):
self.edits = list[list[FileE... | from typing import List
from mentat.errors import HistoryError
from mentat.parsers.file_edit import FileEdit
from mentat.session_context import SESSION_CONTEXT
# TODO: Keep track of when we create directories so we can undo those as well
class EditHistory:
def __init__(self):
self.edits = list[list[FileE... |
27,829 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/interval.py | 22,23 | 1,80 | parse_intervals | 23,40 | 23,40 | from __future__ import annotations
import math
import re
from pathlib import Path
import attr
def split_intervals_from_path(custom_path: str | Path) -> tuple[Path, str]:
match = re.match(
r"(.*?):((\d+-\d+|\d+)(,\d+(-\d+)?)*$)", # One or more intervals/numbers
str(custom_path),
)
if mat... | from __future__ import annotations
import math
import re
from pathlib import Path
import attr
def split_intervals_from_path(custom_path: str | Path) -> tuple[Path, str]:
match = re.match(
r"(.*?):((\d+-\d+|\d+)(,\d+(-\d+)?)*$)", # One or more intervals/numbers
str(custom_path),
)
if mat... | try:
intervals = list[Interval]()
for interval in interval_string.split(","):
interval = interval.split("-", 1)
if len(interval) == 1:
interval = Interval(int(interval[0]), int(interval[0]) + 1)
else:
interval = Interval(int(interva... | try:
intervals = list[Interval]()
for interval in interval_string.split(","):
interval = interval.split("-", 1)
if len(interval) == 1:
interval = Interval(int(interval[0]), int(interval[0]) + 1)
else:
interval = Interval(int(interva... | 61 | 554 | 181 | 735 | from __future__ import annotations
import math
import re
from pathlib import Path
import attr
def split_intervals_from_path(custom_path: str | Path) -> tuple[Path, str]:
match = re.match(
r"(.*?):((\d+-\d+|\d+)(,\d+(-\d+)?)*$)", # One or more intervals/numbers
str(custom_path),
)
if mat... | from __future__ import annotations
import math
import re
from pathlib import Path
import attr
def split_intervals_from_path(custom_path: str | Path) -> tuple[Path, str]:
match = re.match(
r"(.*?):((\d+-\d+|\d+)(,\d+(-\d+)?)*$)", # One or more intervals/numbers
str(custom_path),
)
if mat... | |
27,830 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/interval.py | 67,69 | 43,80 | from_string | Interval | 69,80 | 69,80 | @attr.define(order=True, frozen=True)
class Interval:
"""
1-indexed interval of file lines, inclusive start, exclusive end
"""
start: int | float = attr.field()
end: int | float = attr.field()
def contains(self, line_number: int) -> bool:
return self.start <= line_number < self.end
... | @attr.define(order=True, frozen=True)
class Interval:
"""
1-indexed interval of file lines, inclusive start, exclusive end
"""
start: int | float = attr.field()
end: int | float = attr.field()
def contains(self, line_number: int) -> bool:
return self.start <= line_number < self.end
... | try:
interval_parts = interval_string.split("-")
except ValueError:
return Interval(1, INTERVAL_FILE_END)
if len(interval_parts) != 2:
# corrupt interval string, make it whole file
return Interval(1, INTERVAL_FILE_END)
start, end = interv... | try:
interval_parts = interval_string.split("-")
except ValueError:
return Interval(1, INTERVAL_FILE_END)
if len(interval_parts) != 2:
# corrupt interval string, make it whole file
return Interval(1, INTERVAL_FILE_END)
start, end = interv... | 31 | 257 | 116 | 373 | from __future__ import annotations
import math
import re
from pathlib import Path
import attr
def split_intervals_from_path(custom_path: str | Path) -> tuple[Path, str]:
match = re.match(
r"(.*?):((\d+-\d+|\d+)(,\d+(-\d+)?)*$)", # One or more intervals/numbers
str(custom_path),
)
if mat... | from __future__ import annotations
import math
import re
from pathlib import Path
import attr
def split_intervals_from_path(custom_path: str | Path) -> tuple[Path, str]:
match = re.match(
r"(.*?):((\d+-\d+|\d+)(,\d+(-\d+)?)*$)", # One or more intervals/numbers
str(custom_path),
)
if mat... |
27,831 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/logging_config.py | 11,12 | 1,78 | setup_logging | 12,78 | 12,78 | import datetime
import logging
from mentat.llm_api_handler import is_test_environment
from mentat.utils import mentat_dir_path
logs_dir = "logs"
logs_path = mentat_dir_path / logs_dir
def setup_logging():
FILL_FUNC_BODY | import datetime
import logging
from mentat.llm_api_handler import is_test_environment
from mentat.utils import mentat_dir_path
logs_dir = "logs"
logs_path = mentat_dir_path / logs_dir
def setup_logging():
FILL_FUNC_BODY | if is_test_environment():
return
logging.getLogger("openai").setLevel(logging.WARNING)
# Breaking out of async generator when model messes up causes an error
logging.getLogger("asyncio").setLevel(logging.CRITICAL)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
... | if is_test_environment():
return
logging.getLogger("openai").setLevel(logging.WARNING)
# Breaking out of async generator when model messes up causes an error
logging.getLogger("asyncio").setLevel(logging.CRITICAL)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
... | 172 | 82 | 853 | 935 | import datetime
import logging
from mentat.llm_api_handler import is_test_environment
from mentat.utils import mentat_dir_path
logs_dir = "logs"
logs_path = mentat_dir_path / logs_dir
def setup_logging():
FILL_FUNC_BODY | import datetime
import logging
from mentat.llm_api_handler import is_test_environment
from mentat.utils import mentat_dir_path
logs_dir = "logs"
logs_path = mentat_dir_path / logs_dir
def setup_logging():
FILL_FUNC_BODY | |
27,832 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/parsers/diff_utils.py | 22,23 | 1,29 | _exact_match | 23,29 | 23,29 | def matching_index(orig_lines: list[str], new_lines: list[str]) -> int:
orig_lines = orig_lines.copy()
new_lines = new_lines.copy()
index = _exact_match(orig_lines, new_lines)
if index == -1:
orig_lines = [s.lower() for s in orig_lines]
new_lines = [s.lower() for s in new_lines]
... | def matching_index(orig_lines: list[str], new_lines: list[str]) -> int:
orig_lines = orig_lines.copy()
new_lines = new_lines.copy()
index = _exact_match(orig_lines, new_lines)
if index == -1:
orig_lines = [s.lower() for s in orig_lines]
new_lines = [s.lower() for s in new_lines]
... | if "".join(new_lines).strip() == "" and "".join(orig_lines).strip() == "":
return 0
for i in range(len(orig_lines) - (len(new_lines) - 1)):
if orig_lines[i : i + len(new_lines)] == new_lines:
return i
return -1
| if "".join(new_lines).strip() == "" and "".join(orig_lines).strip() == "":
return 0
for i in range(len(orig_lines) - (len(new_lines) - 1)):
if orig_lines[i : i + len(new_lines)] == new_lines:
return i
return -1
| 30 | 332 | 97 | 429 | def matching_index(orig_lines: list[str], new_lines: list[str]) -> int:
orig_lines = orig_lines.copy()
new_lines = new_lines.copy()
index = _exact_match(orig_lines, new_lines)
if index == -1:
orig_lines = [s.lower() for s in orig_lines]
new_lines = [s.lower() for s in new_lines]
... | def matching_index(orig_lines: list[str], new_lines: list[str]) -> int:
orig_lines = orig_lines.copy()
new_lines = new_lines.copy()
index = _exact_match(orig_lines, new_lines)
if index == -1:
orig_lines = [s.lower() for s in orig_lines]
new_lines = [s.lower() for s in new_lines]
... | |
27,837 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/parsers/streaming_printer.py | 11,12 | 1,92 | send_formatted_string | 12,24 | 12,24 | import asyncio
from collections import deque
from typing import Any, Dict, List, Literal, Tuple
from mentat.session_context import SESSION_CONTEXT
# TODO: Make this a class
FormattedString = str | Tuple[str, Dict[str, Any]] | List[Tuple[str, Dict[str, Any]]]
def send_formatted_string(string: FormattedString):
FILL_... | import asyncio
from collections import deque
from typing import Any, Dict, List, Literal, Tuple
from mentat.session_context import SESSION_CONTEXT
# TODO: Make this a class
FormattedString = str | Tuple[str, Dict[str, Any]] | List[Tuple[str, Dict[str, Any]]]
def send_formatted_string(string: FormattedString):
FILL_... | ctx = SESSION_CONTEXT.get()
if isinstance(string, List):
for line in string:
ctx.stream.send(line[0], **line[1], end="")
ctx.stream.send("")
elif isinstance(string, str):
ctx.stream.send(string)
else:
ctx.stream.send(string[0], **string[1])
| ctx = SESSION_CONTEXT.get()
if isinstance(string, List):
for line in string:
ctx.stream.send(line[0], **line[1], end="")
ctx.stream.send("")
elif isinstance(string, str):
ctx.stream.send(string)
else:
ctx.stream.send(string[0], **string[1])
| 21 | 833 | 115 | 948 | import asyncio
from collections import deque
from typing import Any, Dict, List, Literal, Tuple
from mentat.session_context import SESSION_CONTEXT
# TODO: Make this a class
FormattedString = str | Tuple[str, Dict[str, Any]] | List[Tuple[str, Dict[str, Any]]]
def send_formatted_string(string: FormattedString):
FILL_... | import asyncio
from collections import deque
from typing import Any, Dict, List, Literal, Tuple
from mentat.session_context import SESSION_CONTEXT
# TODO: Make this a class
FormattedString = str | Tuple[str, Dict[str, Any]] | List[Tuple[str, Dict[str, Any]]]
def send_formatted_string(string: FormattedString):
FILL_... | |
27,838 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/parsers/streaming_printer.py | 32,38 | 24,92 | add_string | StreamingPrinter | 38,65 | 38,65 | class StreamingPrinter:
def __init__(self):
self.strings_to_print: deque[Tuple[str, Dict[str, Any]]] = deque()
self.finishing = False
self.shutdown = False
self.cur_file: str | None = None
self.cur_file_display: Tuple[str, Literal["edit", "creation", "deletion", "rename"]] | ... | class StreamingPrinter:
def __init__(self):
self.strings_to_print: deque[Tuple[str, Dict[str, Any]]] = deque()
self.finishing = False
self.shutdown = False
self.cur_file: str | None = None
self.cur_file_display: Tuple[str, Literal["edit", "creation", "deletion", "rename"]] | ... | if self.finishing:
return
if isinstance(formatted_string, List):
for string in formatted_string:
self.add_string(string, end="")
if end and (allow_empty or any(string[0] for string in formatted_string)):
self.add_string(end, end="")
... | if self.finishing:
return
if isinstance(formatted_string, List):
for string in formatted_string:
self.add_string(string, end="")
if end and (allow_empty or any(string[0] for string in formatted_string)):
self.add_string(end, end="")
... | 69 | 475 | 283 | 758 | import asyncio
from collections import deque
from typing import Any, Dict, List, Literal, Tuple
from mentat.session_context import SESSION_CONTEXT
# TODO: Make this a class
FormattedString = str | Tuple[str, Dict[str, Any]] | List[Tuple[str, Dict[str, Any]]]
def send_formatted_string(string: FormattedString):
c... | import asyncio
from collections import deque
from typing import Any, Dict, List, Literal, Tuple
from mentat.session_context import SESSION_CONTEXT
# TODO: Make this a class
FormattedString = str | Tuple[str, Dict[str, Any]] | List[Tuple[str, Dict[str, Any]]]
def send_formatted_string(string: FormattedString):
c... |
27,840 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/prompts/prompts.py | 8,9 | 1,13 | read_prompt | 9,13 | 9,13 | from pathlib import Path
from mentat.utils import fetch_resource
prompts_path = "prompts"
def read_prompt(file_name: Path) -> str:
FILL_FUNC_BODY | from pathlib import Path
from mentat.utils import fetch_resource
prompts_path = "prompts"
def read_prompt(file_name: Path) -> str:
FILL_FUNC_BODY | prompt_resource = fetch_resource(prompts_path / file_name)
with prompt_resource.open("r") as prompt_file:
prompt = prompt_file.read()
return prompt
| prompt_resource = fetch_resource(prompts_path / file_name)
with prompt_resource.open("r") as prompt_file:
prompt = prompt_file.read()
return prompt
| 14 | 59 | 54 | 113 | from pathlib import Path
from mentat.utils import fetch_resource
prompts_path = "prompts"
def read_prompt(file_name: Path) -> str:
FILL_FUNC_BODY | from pathlib import Path
from mentat.utils import fetch_resource
prompts_path = "prompts"
def read_prompt(file_name: Path) -> str:
FILL_FUNC_BODY | |
27,841 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/python_client/client.py | 87,88 | 13,136 | _accumulate_messages | PythonClient | 88,94 | 88,94 | class PythonClient:
"""A client for interacting with Mentat in python."""
def __init__(
self,
cwd: Path = Path.cwd(),
paths: List[Path] = [],
exclude_paths: List[Path] = [],
ignore_paths: List[Path] = [],
diff: str | None = None,
pr_diff: str | None = Non... | class PythonClient:
"""A client for interacting with Mentat in python."""
def __init__(
self,
cwd: Path = Path.cwd(),
paths: List[Path] = [],
exclude_paths: List[Path] = [],
ignore_paths: List[Path] = [],
diff: str | None = None,
pr_diff: str | None = Non... | async for message in self.session.stream.listen():
end = "\n"
if isinstance(message.extra.get("end"), str):
end = message.extra["end"]
self._accumulated_message += message.data + end
| async for message in self.session.stream.listen():
end = "\n"
if isinstance(message.extra.get("end"), str):
end = message.extra["end"]
self._accumulated_message += message.data + end
| 19 | 1,273 | 69 | 1,342 | import asyncio
from asyncio import Event
from asyncio.tasks import Task
from pathlib import Path
from typing import List
from mentat.config import Config
from mentat.errors import MentatError
from mentat.session import Session
from mentat.session_stream import StreamMessageSource
class PythonClient:
"""A client ... | import asyncio
from asyncio import Event
from asyncio.tasks import Task
from pathlib import Path
from typing import List
from mentat.config import Config
from mentat.errors import MentatError
from mentat.session import Session
from mentat.session_stream import StreamMessageSource
class PythonClient:
"""A client ... |
27,842 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/sampler/sample.py | 40,42 | 13,113 | load | Sample | 42,68 | 42,68 | @attr.define
class Sample:
# TODO: enforce required fields
title: str = attr.field(default="")
description: str = attr.field(default="")
id: str = attr.field(default="")
parent_id: str = attr.field(default="")
repo: str = attr.field(default="")
environment_setup_commit: str | None = attr.fie... | @attr.define
class Sample:
# TODO: enforce required fields
title: str = attr.field(default="")
description: str = attr.field(default="")
id: str = attr.field(default="")
parent_id: str = attr.field(default="")
repo: str = attr.field(default="")
environment_setup_commit: str | None = attr.fie... | with open(fname, "r") as f:
kwargs = json.load(f)
_version = kwargs.get("version")
if _version and _version < "0.2.0":
kwargs["message_history"] = kwargs.get("message_history", [])[::-1]
kwargs["version"] = "0.2.0"
_version = kw... | with open(fname, "r") as f:
kwargs = json.load(f)
_version = kwargs.get("version")
if _version and _version < "0.2.0":
kwargs["message_history"] = kwargs.get("message_history", [])[::-1]
kwargs["version"] = "0.2.0"
_version = kw... | 87 | 1,140 | 367 | 1,507 | from __future__ import annotations
import json
import re
from pathlib import Path
import attr
from mentat.errors import SampleError
from mentat.sampler import __version__
@attr.define
class Sample:
# TODO: enforce required fields
title: str = attr.field(default="")
description: str = attr.field(default... | from __future__ import annotations
import json
import re
from pathlib import Path
import attr
from mentat.errors import SampleError
from mentat.sampler import __version__
@attr.define
class Sample:
# TODO: enforce required fields
title: str = attr.field(default="")
description: str = attr.field(default... |
27,843 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/sampler/utils.py | 101,102 | 1,139 | get_active_snapshot_commit | 103,139 | 102,139 | import os
from pathlib import Path
from typing import Optional
from uuid import uuid4
from git import GitCommandError, Repo # type: ignore
from mentat.errors import SampleError
from mentat.git_handler import get_non_gitignored_files
from mentat.utils import is_file_text_encoded
CLONE_TO_DIR = Path("benchmarks/bench... | import os
from pathlib import Path
from typing import Optional
from uuid import uuid4
from git import GitCommandError, Repo # type: ignore
from mentat.errors import SampleError
from mentat.git_handler import get_non_gitignored_files
from mentat.utils import is_file_text_encoded
CLONE_TO_DIR = Path("benchmarks/bench... | if not repo.is_dirty() and not repo.untracked_files:
return None
if not repo.config_reader().has_option("user", "name"):
raise SampleError("ERROR: Git user.name not set. Please run 'git config --global user.name" ' "Your Name"\'.')
try:
# Stash active changes and record the current p... | """Returns the commit hash of the current active snapshot, or None if there are no active changes."""
if not repo.is_dirty() and not repo.untracked_files:
return None
if not repo.config_reader().has_option("user", "name"):
raise SampleError("ERROR: Git user.name not set. Please run 'git conf... | 144 | 1,066 | 484 | 1,550 | import os
from pathlib import Path
from typing import Optional
from uuid import uuid4
from git import GitCommandError, Repo # type: ignore
from mentat.errors import SampleError
from mentat.git_handler import get_non_gitignored_files
from mentat.utils import is_file_text_encoded
CLONE_TO_DIR = Path("benchmarks/bench... | import os
from pathlib import Path
from typing import Optional
from uuid import uuid4
from git import GitCommandError, Repo # type: ignore
from mentat.errors import SampleError
from mentat.git_handler import get_non_gitignored_files
from mentat.utils import is_file_text_encoded
CLONE_TO_DIR = Path("benchmarks/bench... | |
27,844 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/sentry.py | 33,34 | 1,55 | sentry_init | 34,55 | 34,55 | import os
import platform
from uuid import UUID, uuid4
import sentry_sdk
from mentat.app_conf import IS_DEV
from mentat.utils import mentat_dir_path
from mentat.version import __version__
user_id_path = mentat_dir_path / ".user"
def _new_user() -> UUID:
user = uuid4()
with user_id_path.open("w") as uuid_fi... | import os
import platform
from uuid import UUID, uuid4
import sentry_sdk
from mentat.app_conf import IS_DEV
from mentat.utils import mentat_dir_path
from mentat.version import __version__
user_id_path = mentat_dir_path / ".user"
def _new_user() -> UUID:
user = uuid4()
with user_id_path.open("w") as uuid_fi... | # Check if in dev or testing (although we should never be in testing in prod)
if IS_DEV or "PYTEST_CURRENT_TEST" in os.environ:
return
sentry_sdk.init(
dsn="https://fa4d2b80dab0938c38c89384dc317f1b@o4506146491006976.ingest.sentry.io/4506187066245120",
profiles_sample_rate=1.0,
... | # Check if in dev or testing (although we should never be in testing in prod)
if IS_DEV or "PYTEST_CURRENT_TEST" in os.environ:
return
sentry_sdk.init(
dsn="https://fa4d2b80dab0938c38c89384dc317f1b@o4506146491006976.ingest.sentry.io/4506187066245120",
profiles_sample_rate=1.0,
... | 48 | 245 | 299 | 544 | import os
import platform
from uuid import UUID, uuid4
import sentry_sdk
from mentat.app_conf import IS_DEV
from mentat.utils import mentat_dir_path
from mentat.version import __version__
user_id_path = mentat_dir_path / ".user"
def _new_user() -> UUID:
user = uuid4()
with user_id_path.open("w") as uuid_fi... | import os
import platform
from uuid import UUID, uuid4
import sentry_sdk
from mentat.app_conf import IS_DEV
from mentat.utils import mentat_dir_path
from mentat.version import __version__
user_id_path = mentat_dir_path / ".user"
def _new_user() -> UUID:
user = uuid4()
with user_id_path.open("w") as uuid_fi... | |
27,845 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/server/mentat_server.py | 72,73 | 1,81 | main | 73,81 | 73,81 | import argparse
import asyncio
import logging
from asyncio import CancelledError, Event
from io import TextIOWrapper
from pathlib import Path
from mentat.config import Config
from mentat.session import Session
from mentat.session_stream import StreamMessage, StreamMessageSource
async def ainput(fd_input: TextIOWrapp... | import argparse
import asyncio
import logging
from asyncio import CancelledError, Event
from io import TextIOWrapper
from pathlib import Path
from mentat.config import Config
from mentat.session import Session
from mentat.session_stream import StreamMessage, StreamMessageSource
async def ainput(fd_input: TextIOWrapp... | parser = argparse.ArgumentParser(
description="Run conversation with command line args",
)
parser.add_argument("cwd", help="The working directory for the server to run in")
Config.add_fields_to_argparse(parser)
args = parser.parse_args()
asyncio.run(run(args))
| parser = argparse.ArgumentParser(
description="Run conversation with command line args",
)
parser.add_argument("cwd", help="The working directory for the server to run in")
Config.add_fields_to_argparse(parser)
args = parser.parse_args()
asyncio.run(run(args))
| 25 | 683 | 94 | 777 | import argparse
import asyncio
import logging
from asyncio import CancelledError, Event
from io import TextIOWrapper
from pathlib import Path
from mentat.config import Config
from mentat.session import Session
from mentat.session_stream import StreamMessage, StreamMessageSource
async def ainput(fd_input: TextIOWrapp... | import argparse
import asyncio
import logging
from asyncio import CancelledError, Event
from io import TextIOWrapper
from pathlib import Path
from mentat.config import Config
from mentat.session import Session
from mentat.session_stream import StreamMessage, StreamMessageSource
async def ainput(fd_input: TextIOWrapp... | |
27,846 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/server/mentat_server.py | 23,24 | 17,62 | _client_listener | MentatServer | 24,36 | 24,36 | class MentatServer:
def __init__(self, cwd: Path, config: Config) -> None:
self.cwd = cwd
self.stopped = Event()
self.session = Session(self.cwd, config=config, apply_edits=False, show_update=False)
async def _client_listener(self):
FILL_FUNC_BODY async def _stream_listener(self):
... | class MentatServer:
def __init__(self, cwd: Path, config: Config) -> None:
self.cwd = cwd
self.stopped = Event()
self.session = Session(self.cwd, config=config, apply_edits=False, show_update=False)
async def _client_listener(self):
FILL_FUNC_BODY async def _stream_listener(self):
... | with open(3) as fd_input:
try:
while not self.stopped.is_set():
line = await ainput(fd_input)
try:
message = StreamMessage.model_validate_json(line) # pyright: ignore
self.session.stream.send_str... | with open(3) as fd_input:
try:
while not self.stopped.is_set():
line = await ainput(fd_input)
try:
message = StreamMessage.model_validate_json(line) # pyright: ignore
self.session.stream.send_str... | 32 | 347 | 141 | 488 | import argparse
import asyncio
import logging
from asyncio import CancelledError, Event
from io import TextIOWrapper
from pathlib import Path
from mentat.config import Config
from mentat.session import Session
from mentat.session_stream import StreamMessage, StreamMessageSource
async def ainput(fd_input: TextIOWrapp... | import argparse
import asyncio
import logging
from asyncio import CancelledError, Event
from io import TextIOWrapper
from pathlib import Path
from mentat.config import Config
from mentat.session import Session
from mentat.session_stream import StreamMessage, StreamMessageSource
async def ainput(fd_input: TextIOWrapp... |
27,848 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/session_input.py | 11,12 | 1,62 | _get_input_request | 12,24 | 12,24 | import logging
import shlex
from typing import Any
from mentat.command.command import Command
from mentat.errors import SessionExit
from mentat.session_context import SESSION_CONTEXT
from mentat.session_stream import StreamMessage
async def _get_input_request(log_input: bool, **kwargs: Any) -> StreamMessage:
FILL_FU... | import logging
import shlex
from typing import Any
from mentat.command.command import Command
from mentat.errors import SessionExit
from mentat.session_context import SESSION_CONTEXT
from mentat.session_stream import StreamMessage
async def _get_input_request(log_input: bool, **kwargs: Any) -> StreamMessage:
FILL_FU... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
message = stream.send("", channel="input_request", **kwargs)
response = await stream.recv(f"input_request:{message.id}")
if log_input:
logging.debug(f"User Input: {response.data}")
else:
logging.debug("User ... | session_context = SESSION_CONTEXT.get()
stream = session_context.stream
message = stream.send("", channel="input_request", **kwargs)
response = await stream.recv(f"input_request:{message.id}")
if log_input:
logging.debug(f"User Input: {response.data}")
else:
logging.debug("User ... | 26 | 573 | 123 | 696 | import logging
import shlex
from typing import Any
from mentat.command.command import Command
from mentat.errors import SessionExit
from mentat.session_context import SESSION_CONTEXT
from mentat.session_stream import StreamMessage
async def _get_input_request(log_input: bool, **kwargs: Any) -> StreamMessage:
FILL_FU... | import logging
import shlex
from typing import Any
from mentat.command.command import Command
from mentat.errors import SessionExit
from mentat.session_context import SESSION_CONTEXT
from mentat.session_stream import StreamMessage
async def _get_input_request(log_input: bool, **kwargs: Any) -> StreamMessage:
FILL_FU... | |
27,849 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/session_stream.py | 157,158 | 29,195 | universal_listen | SessionStream | 158,162 | 158,162 | class SessionStream:
"""
Used to send and receive messages from the client.
Channels and their expected behavior (starred channels are sent by the client):
default: Any data sent to the client over this channel should be displayed.
Valid kwargs: color, style, filepath, filepath_display, delimiter
... | class SessionStream:
"""
Used to send and receive messages from the client.
Channels and their expected behavior (starred channels are sent by the client):
default: Any data sent to the client over this channel should be displayed.
Valid kwargs: color, style, filepath, filepath_display, delimiter
... | with self._broadcast.universal_subscribe() as subscriber:
async for event in subscriber:
yield event.message
| with self._broadcast.universal_subscribe() as subscriber:
async for event in subscriber:
yield event.message
| 11 | 1,691 | 38 | 1,729 | from __future__ import annotations
import asyncio
import logging
from contextlib import asynccontextmanager
from typing import Any, AsyncGenerator, Dict, List, Literal, cast
from uuid import UUID, uuid4
from pydantic import BaseModel
from mentat.broadcast import Broadcast
class StreamMessageSource:
# Enums can... | from __future__ import annotations
import asyncio
import logging
from contextlib import asynccontextmanager
from typing import Any, AsyncGenerator, Dict, List, Literal, cast
from uuid import UUID, uuid4
from pydantic import BaseModel
from mentat.broadcast import Broadcast
class StreamMessageSource:
# Enums can... |
27,850 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/splash_messages.py | 35,36 | 1,87 | check_version | 36,72 | 36,72 | import re
from typing import Optional
import packaging.version
import requests
from mentat.session_context import SESSION_CONTEXT
from mentat.utils import mentat_dir_path
from mentat.version import __version__
def get_changelog() -> Optional[str]:
try:
response = requests.get("https://raw.githubusercont... | import re
from typing import Optional
import packaging.version
import requests
from mentat.session_context import SESSION_CONTEXT
from mentat.utils import mentat_dir_path
from mentat.version import __version__
def get_changelog() -> Optional[str]:
try:
response = requests.get("https://raw.githubusercont... | ctx = SESSION_CONTEXT.get()
try:
response = requests.get("https://pypi.org/pypi/mentat/json")
data = response.json()
latest_version = data["info"]["version"]
if packaging.version.parse(__version__) < packaging.version.parse(latest_version):
ctx.stream.send(
... | ctx = SESSION_CONTEXT.get()
try:
response = requests.get("https://pypi.org/pypi/mentat/json")
data = response.json()
latest_version = data["info"]["version"]
if packaging.version.parse(__version__) < packaging.version.parse(latest_version):
ctx.stream.send(
... | 110 | 471 | 503 | 974 | import re
from typing import Optional
import packaging.version
import requests
from mentat.session_context import SESSION_CONTEXT
from mentat.utils import mentat_dir_path
from mentat.version import __version__
def get_changelog() -> Optional[str]:
try:
response = requests.get("https://raw.githubusercont... | import re
from typing import Optional
import packaging.version
import requests
from mentat.session_context import SESSION_CONTEXT
from mentat.utils import mentat_dir_path
from mentat.version import __version__
def get_changelog() -> Optional[str]:
try:
response = requests.get("https://raw.githubusercont... | |
27,852 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/terminal/client.py | 80,81 | 19,210 | _listen_for_context_updates | TerminalClient | 81,113 | 81,113 | class TerminalClient:
def __init__(
self,
cwd: Path = Path.cwd(),
paths: List[str] = [],
exclude_paths: List[str] = [],
ignore_paths: List[str] = [],
diff: str | None = None,
pr_diff: str | None = None,
config: Config = Config(),
# Used for tes... | class TerminalClient:
def __init__(
self,
cwd: Path = Path.cwd(),
paths: List[str] = [],
exclude_paths: List[str] = [],
ignore_paths: List[str] = [],
diff: str | None = None,
pr_diff: str | None = None,
config: Config = Config(),
# Used for tes... | async for message in self.session.stream.listen("context_update"):
data: ContextStreamMessage = message.data
(
cwd,
diff_context_display,
auto_context_tokens,
features,
git_diff_paths,
git_unt... | async for message in self.session.stream.listen("context_update"):
data: ContextStreamMessage = message.data
(
cwd,
diff_context_display,
auto_context_tokens,
features,
git_diff_paths,
git_unt... | 48 | 1,662 | 297 | 1,959 | from __future__ import annotations
import argparse
import asyncio
import logging
from asyncio import Event
from pathlib import Path
from typing import Any, Coroutine, List, Set
from textual.app import AutopilotCallbackType
from mentat.code_context import ContextStreamMessage
from mentat.config import Config
from men... | from __future__ import annotations
import argparse
import asyncio
import logging
from asyncio import Event
from pathlib import Path
from typing import Any, Coroutine, List, Set
from textual.app import AutopilotCallbackType
from mentat.code_context import ContextStreamMessage
from mentat.config import Config
from men... |
27,853 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/terminal/history_suggester.py | 51,52 | 8,53 | just_moved | HistorySuggester | 52,53 | 52,53 | class HistorySuggester(Suggester):
def __init__(self, history_file: Path, *, case_sensitive: bool = True) -> None:
self.history_file = history_file
self.position = -1
if not history_file.exists():
with open(self.history_file, "w") as f:
pass
with open(self... | class HistorySuggester(Suggester):
def __init__(self, history_file: Path, *, case_sensitive: bool = True) -> None:
self.history_file = history_file
self.position = -1
if not history_file.exists():
with open(self.history_file, "w") as f:
pass
with open(self... | return self._suggestions[self.position] == value
| return self._suggestions[self.position] == value
| 4 | 515 | 15 | 530 | from pathlib import Path
from git import Optional
from textual.suggester import Suggester
from typing_extensions import override
class HistorySuggester(Suggester):
def __init__(self, history_file: Path, *, case_sensitive: bool = True) -> None:
self.history_file = history_file
self.position = -1
... | from pathlib import Path
from git import Optional
from textual.suggester import Suggester
from typing_extensions import override
class HistorySuggester(Suggester):
def __init__(self, history_file: Path, *, case_sensitive: bool = True) -> None:
self.history_file = history_file
self.position = -1
... |
27,854 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/terminal/patched_autocomplete.py | 19,21 | 13,33 | _select_item | PatchedAutoComplete | 21,33 | 21,33 | class PatchedAutoComplete(AutoComplete):
"""
We want more fine control over replacing the text when a completion is
selected, so we patch _select_item.
"""
@override
def _select_item(self):
FILL_FUNC_BODY | class PatchedAutoComplete(AutoComplete):
"""
We want more fine control over replacing the text when a completion is
selected, so we patch _select_item.
"""
@override
def _select_item(self):
FILL_FUNC_BODY | selected: CompletionDropdownItem | None = self.dropdown.selected_item # pyright: ignore
if self.dropdown.display and selected is not None:
cursor_position: int = self.input.cursor_position # pyright: ignore
before = self.input.value[: cursor_position + selected.position]
... | selected: CompletionDropdownItem | None = self.dropdown.selected_item # pyright: ignore
if self.dropdown.display and selected is not None:
cursor_position: int = self.input.cursor_position # pyright: ignore
before = self.input.value[: cursor_position + selected.position]
... | 50 | 69 | 171 | 240 | from dataclasses import dataclass
from typing import List
from textual import events
from textual_autocomplete import AutoComplete, Dropdown, DropdownItem
from typing_extensions import override
from mentat.auto_completer import Completion
from mentat.session_stream import SessionStream, StreamMessageSource
from menta... | from dataclasses import dataclass
from typing import List
from textual import events
from textual_autocomplete import AutoComplete, Dropdown, DropdownItem
from typing_extensions import override
from mentat.auto_completer import Completion
from mentat.session_stream import SessionStream, StreamMessageSource
from menta... |
27,855 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/terminal/patched_autocomplete.py | 62,64 | 43,184 | on_mount | PatchedDropdown | 64,94 | 64,94 | class PatchedDropdown(Dropdown):
"""
The dropdown class in textual_autocomplete isn't able to do everything we need it to (mainly async completions),
so this class patchs some of its methods to add the functionality we need.
"""
@override
def __init__(
self,
stream: SessionStrea... | class PatchedDropdown(Dropdown):
"""
The dropdown class in textual_autocomplete isn't able to do everything we need it to (mainly async completions),
so this class patchs some of its methods to add the functionality we need.
"""
@override
def __init__(
self,
stream: SessionStrea... | screen_layers = list(self.screen.styles.layers)
if "textual-autocomplete" not in screen_layers:
screen_layers.append("textual-autocomplete")
self.screen.styles.layers = tuple(screen_layers) # type: ignore
self.watch(
self.input_widget,
attribute_nam... | screen_layers = list(self.screen.styles.layers)
if "textual-autocomplete" not in screen_layers:
screen_layers.append("textual-autocomplete")
self.screen.styles.layers = tuple(screen_layers) # type: ignore
self.watch(
self.input_widget,
attribute_nam... | 49 | 1,216 | 296 | 1,512 | from dataclasses import dataclass
from typing import List
from textual import events
from textual_autocomplete import AutoComplete, Dropdown, DropdownItem
from typing_extensions import override
from mentat.auto_completer import Completion
from mentat.session_stream import SessionStream, StreamMessageSource
from menta... | from dataclasses import dataclass
from typing import List
from textual import events
from textual_autocomplete import AutoComplete, Dropdown, DropdownItem
from typing_extensions import override
from mentat.auto_completer import Completion
from mentat.session_stream import SessionStream, StreamMessageSource
from menta... |
27,856 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/terminal/terminal_app.py | 92,93 | 31,128 | action_history_up | ContentContainer | 93,99 | 93,99 | class ContentContainer(Static):
BINDINGS = [
("up", "history_up", "Move up in history"),
("down", "history_down", "Move down in history"),
]
def __init__(
self,
stream: SessionStream,
theme: dict[str, str],
renderable: RenderableType = "",
**kwargs: A... | class ContentContainer(Static):
BINDINGS = [
("up", "history_up", "Move up in history"),
("down", "history_down", "Move down in history"),
]
def __init__(
self,
stream: SessionStream,
theme: dict[str, str],
renderable: RenderableType = "",
**kwargs: A... | history = self.suggester.move_up()
if history is not None:
user_input = self.query_one(Input)
user_input.value = history
user_input.cursor_position = len(history)
| history = self.suggester.move_up()
if history is not None:
user_input = self.query_one(Input)
user_input.value = history
user_input.cursor_position = len(history)
| 17 | 993 | 67 | 1,060 | from __future__ import annotations
import os
from asyncio import Event
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set
from rich.console import RenderableType
from rich.markup import escape
from textual import on
from textual.app import App, ComposeResult
from textual.widgets... | from __future__ import annotations
import os
from asyncio import Event
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set
from rich.console import RenderableType
from rich.markup import escape
from textual import on
from textual.app import App, ComposeResult
from textual.widgets... |
27,857 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/terminal/terminal_app.py | 186,197 | 128,221 | update_context | ContextContainer | 197,221 | 197,221 | class ContextContainer(Static):
def _build_path_tree(self, files: list[str], cwd: Path):
"""Builds a tree of paths from a list of CodeFiles."""
tree = dict[str, Any]()
for file in files:
path = os.path.relpath(file, cwd)
parts = Path(path).parts
current_le... | class ContextContainer(Static):
def _build_path_tree(self, files: list[str], cwd: Path):
"""Builds a tree of paths from a list of CodeFiles."""
tree = dict[str, Any]()
for file in files:
path = os.path.relpath(file, cwd)
parts = Path(path).parts
current_le... | feature_tree = self._build_tree_widget(features, cwd, git_diff_paths, git_untracked_paths)
context_header = ""
context_header += "[blue bold]Code Context:[/blue bold]"
context_header += f"\nTokens: [yellow]{total_tokens}[/yellow]"
context_header += f"\nTotal Session Cost: [yello... | feature_tree = self._build_tree_widget(features, cwd, git_diff_paths, git_untracked_paths)
context_header = ""
context_header += "[blue bold]Code Context:[/blue bold]"
context_header += f"\nTokens: [yellow]{total_tokens}[/yellow]"
context_header += f"\nTotal Session Cost: [yello... | 65 | 677 | 322 | 999 | from __future__ import annotations
import os
from asyncio import Event
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set
from rich.console import RenderableType
from rich.markup import escape
from textual import on
from textual.app import App, ComposeResult
from textual.widgets... | from __future__ import annotations
import os
from asyncio import Event
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set
from rich.console import RenderableType
from rich.markup import escape
from textual import on
from textual.app import App, ComposeResult
from textual.widgets... |
27,858 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/terminal/terminal_app.py | 245,246 | 226,325 | display_stream_message | TerminalApp | 246,283 | 246,283 | class TerminalApp(App[None]):
BINDINGS = [("ctrl+c", "on_interrupt", "Send interrupt")]
CSS = css
TITLE = "Mentat"
def __init__(self, client: TerminalClient, **kwargs: Any):
self.client = client
self.command_autocomplete = False
self.last_filepath = None
super().__init__... | class TerminalApp(App[None]):
BINDINGS = [("ctrl+c", "on_interrupt", "Send interrupt")]
CSS = css
TITLE = "Mentat"
def __init__(self, client: TerminalClient, **kwargs: Any):
self.client = client
self.command_autocomplete = False
self.last_filepath = None
super().__init__... | end = "\n"
color = None
content_container = self.query_one(ContentContainer)
if isinstance(message.extra.get("end"), str):
end = message.extra["end"]
if isinstance(message.extra.get("color"), str):
color = message.extra["color"]
if isinstance(mess... | end = "\n"
color = None
content_container = self.query_one(ContentContainer)
if isinstance(message.extra.get("end"), str):
end = message.extra["end"]
if isinstance(message.extra.get("color"), str):
color = message.extra["color"]
if isinstance(mess... | 88 | 634 | 451 | 1,085 | from __future__ import annotations
import os
from asyncio import Event
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set
from rich.console import RenderableType
from rich.markup import escape
from textual import on
from textual.app import App, ComposeResult
from textual.widgets... | from __future__ import annotations
import os
from asyncio import Event
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set
from rich.console import RenderableType
from rich.markup import escape
from textual import on
from textual.app import App, ComposeResult
from textual.widgets... |
27,859 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/transcripts.py | 34,35 | 1,52 | get_transcript_logs | 35,52 | 35,52 | import glob
import json
import re
from typing import TypedDict
from openai.types.chat import ChatCompletionContentPartParam, ChatCompletionMessageParam
from mentat.logging_config import logs_path
class UserMessage(TypedDict):
message: list[ChatCompletionContentPartParam] | str
# We need this field so that i... | import glob
import json
import re
from typing import TypedDict
from openai.types.chat import ChatCompletionContentPartParam, ChatCompletionMessageParam
from mentat.logging_config import logs_path
class UserMessage(TypedDict):
message: list[ChatCompletionContentPartParam] | str
# We need this field so that i... | transcripts = glob.glob(str(logs_path / "transcript_*"))
ans = list[Transcript]()
for transcript_path in transcripts:
match = re.search(r"transcript_(.+).log", transcript_path)
if match is None:
continue
timestamp = match.group(1)
with open(transcript_path, "r") ... | transcripts = glob.glob(str(logs_path / "transcript_*"))
ans = list[Transcript]()
for transcript_path in transcripts:
match = re.search(r"transcript_(.+).log", transcript_path)
if match is None:
continue
timestamp = match.group(1)
with open(transcript_path, "r") ... | 53 | 266 | 210 | 476 | import glob
import json
import re
from typing import TypedDict
from openai.types.chat import ChatCompletionContentPartParam, ChatCompletionMessageParam
from mentat.logging_config import logs_path
class UserMessage(TypedDict):
message: list[ChatCompletionContentPartParam] | str
# We need this field so that i... | import glob
import json
import re
from typing import TypedDict
from openai.types.chat import ChatCompletionContentPartParam, ChatCompletionMessageParam
from mentat.logging_config import logs_path
class UserMessage(TypedDict):
message: list[ChatCompletionContentPartParam] | str
# We need this field so that i... | |
27,860 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/utils.py | 61,62 | 1,131 | create_viewer | 62,75 | 62,75 | from __future__ import annotations
import asyncio
import hashlib
from importlib import resources
from importlib.abc import Traversable
from pathlib import Path
from typing import TYPE_CHECKING, AsyncIterator, List, Literal, Optional, Union
from jinja2 import Environment, PackageLoader, select_autoescape
if TYPE_CHEC... | from __future__ import annotations
import asyncio
import hashlib
from importlib import resources
from importlib.abc import Traversable
from pathlib import Path
from typing import TYPE_CHECKING, AsyncIterator, List, Literal, Optional, Union
from jinja2 import Environment, PackageLoader, select_autoescape
if TYPE_CHEC... | env = Environment(
loader=PackageLoader("mentat", "resources/templates"),
autoescape=select_autoescape(["html", "xml"]),
)
template = env.get_template("conversation_viewer.jinja")
html = template.render(transcripts=transcripts[:500])
viewer_path = mentat_dir_path / conversation_view... | env = Environment(
loader=PackageLoader("mentat", "resources/templates"),
autoescape=select_autoescape(["html", "xml"]),
)
template = env.get_template("conversation_viewer.jinja")
html = template.render(transcripts=transcripts[:500])
viewer_path = mentat_dir_path / conversation_view... | 26 | 1,145 | 154 | 1,299 | from __future__ import annotations
import asyncio
import hashlib
from importlib import resources
from importlib.abc import Traversable
from pathlib import Path
from typing import TYPE_CHECKING, AsyncIterator, List, Literal, Optional, Union
from jinja2 import Environment, PackageLoader, select_autoescape
if TYPE_CHEC... | from __future__ import annotations
import asyncio
import hashlib
from importlib import resources
from importlib.abc import Traversable
from pathlib import Path
from typing import TYPE_CHECKING, AsyncIterator, List, Literal, Optional, Union
from jinja2 import Environment, PackageLoader, select_autoescape
if TYPE_CHEC... | |
27,861 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/mentat/vision/vision_manager.py | 75,76 | 25,111 | screenshot | VisionManager | 76,108 | 76,108 | @attr.define
class VisionManager:
driver: Optional[WebDriver] = attr.field(default=None)
def _open_browser(self) -> None:
ctx = SESSION_CONTEXT.get()
safari_installed = False
if self.driver is None or not self.driver_running():
try:
self.driver = webdriver.Sa... | @attr.define
class VisionManager:
driver: Optional[WebDriver] = attr.field(default=None)
def _open_browser(self) -> None:
ctx = SESSION_CONTEXT.get()
safari_installed = False
if self.driver is None or not self.driver_running():
try:
self.driver = webdriver.Sa... | ctx = SESSION_CONTEXT.get()
if path is not None:
expanded = os.path.abspath(os.path.expanduser(path))
browser_path = path
if os.path.exists(expanded):
browser_path = "file://" + expanded
else:
if not path.startswith("http"):... | ctx = SESSION_CONTEXT.get()
if path is not None:
expanded = os.path.abspath(os.path.expanduser(path))
browser_path = path
if os.path.exists(expanded):
browser_path = "file://" + expanded
else:
if not path.startswith("http"):... | 86 | 489 | 342 | 831 | import base64
import os
from typing import Optional
import attr
from selenium import webdriver
from selenium.common.exceptions import NoSuchWindowException, WebDriverException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdrive... | import base64
import os
from typing import Optional
import attr
from selenium import webdriver
from selenium.common.exceptions import NoSuchWindowException, WebDriverException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdrive... |
27,862 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/scripts/sampler/validate.py | 7,8 | 1,36 | validate_sample | 9,36 | 8,36 | from pathlib import Path
from mentat.errors import SampleError
from mentat.sampler.utils import apply_diff_to_repo, setup_repo
async def validate_sample(sample, cwd: Path | str | None = None) -> tuple[bool, str]:
FILL_FUNC_BODY | from pathlib import Path
from mentat.errors import SampleError
from mentat.sampler.utils import apply_diff_to_repo, setup_repo
async def validate_sample(sample, cwd: Path | str | None = None) -> tuple[bool, str]:
"""Validate a sample by applying diffs and checking sample fields."""
FILL_FUNC_BODY | try:
required_fields = ["id", "repo", "merge_base", "message_prompt"]
for field in required_fields:
if not getattr(sample, field):
return False, f"Missing required field: {field}"
if not sample.message_edit and not sample.diff_edit:
return False, "Samp... | """Validate a sample by applying diffs and checking sample fields."""
try:
required_fields = ["id", "repo", "merge_base", "message_prompt"]
for field in required_fields:
if not getattr(sample, field):
return False, f"Missing required field: {field}"
if not sam... | 85 | 93 | 301 | 394 | from pathlib import Path
from mentat.errors import SampleError
from mentat.sampler.utils import apply_diff_to_repo, setup_repo
async def validate_sample(sample, cwd: Path | str | None = None) -> tuple[bool, str]:
FILL_FUNC_BODY | from pathlib import Path
from mentat.errors import SampleError
from mentat.sampler.utils import apply_diff_to_repo, setup_repo
async def validate_sample(sample, cwd: Path | str | None = None) -> tuple[bool, str]:
"""Validate a sample by applying diffs and checking sample fields."""
FILL_FUNC_BODY | |
27,863 | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat | /home/hieuvd/dung_repo/raw/stars_02/AbanteAI_mentat/mentat/scripts/translate_transcript.py | 18,19 | 1,66 | translate_message | 19,25 | 19,25 | #!/usr/bin/env python
import argparse
import asyncio
import json
from pathlib import Path
from unittest.mock import AsyncMock
from mentat.code_file_manager import CodeFileManager
from mentat.parsers.git_parser import GitParser
from mentat.parsers.parser import Parser
from mentat.parsers.parser_map import parser_map
fr... | #!/usr/bin/env python
import argparse
import asyncio
import json
from pathlib import Path
from unittest.mock import AsyncMock
from mentat.code_file_manager import CodeFileManager
from mentat.parsers.git_parser import GitParser
from mentat.parsers.parser import Parser
from mentat.parsers.parser_map import parser_map
fr... | parsedLLMResponse = asyncio.run(
starting_parser.stream_and_parse_llm_response(convert_string_to_asynciter(message, 100))
)
return ending_parser.file_edits_to_llm_message(parsedLLMResponse)
| parsedLLMResponse = asyncio.run(
starting_parser.stream_and_parse_llm_response(convert_string_to_asynciter(message, 100))
)
return ending_parser.file_edits_to_llm_message(parsedLLMResponse)
| 8 | 620 | 81 | 701 | #!/usr/bin/env python
import argparse
import asyncio
import json
from pathlib import Path
from unittest.mock import AsyncMock
from mentat.code_file_manager import CodeFileManager
from mentat.parsers.git_parser import GitParser
from mentat.parsers.parser import Parser
from mentat.parsers.parser_map import parser_map
fr... | #!/usr/bin/env python
import argparse
import asyncio
import json
from pathlib import Path
from unittest.mock import AsyncMock
from mentat.code_file_manager import CodeFileManager
from mentat.parsers.git_parser import GitParser
from mentat.parsers.parser import Parser
from mentat.parsers.parser_map import parser_map
fr... | |
27,864 | /home/hieuvd/dung_repo/raw/stars_02/Accenture_AmpliGraph/AmpliGraph | /home/hieuvd/dung_repo/raw/stars_02/Accenture_AmpliGraph/AmpliGraph/ampligraph/latent_features/layers/scoring/HolE.py | 69,70 | 12,90 | _get_object_corruption_scores | HolE | 86,90 | 70,90 | @register_layer("HolE")
class HolE(ComplEx):
r"""Holographic Embeddings (HolE) scoring layer.
The HolE model :cite:`nickel2016holographic` as re-defined by Hayashi et al. :cite:`HayashiS17`:
.. math::
f_{HolE}= \frac{2}{k} \, f_{ComplEx}
where :math:`k` is the size of the embeddings.
"""
... | @register_layer("HolE")
class HolE(ComplEx):
r"""Holographic Embeddings (HolE) scoring layer.
The HolE model :cite:`nickel2016holographic` as re-defined by Hayashi et al. :cite:`HayashiS17`:
.. math::
f_{HolE}= \frac{2}{k} \, f_{ComplEx}
where :math:`k` is the size of the embeddings.
"""
... | # HolE scoring is 2/k * complex_score
return (2 / (self.internal_k / 2)) * (
super()._get_object_corruption_scores(triples, ent_matrix)
)
| """Compute object corruption scores.
Evaluate the inputs against object corruptions and scores of the corruptions.
Parameters
----------
triples: array-like, shape (n, k)
Batch of input embeddings.
ent_matrix: array-like, shape (m, k)
Slice of em... | 18 | 720 | 63 | 783 | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
from .AbstractScoringLayer import register_layer
from .ComplEx import ComplEx
... | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
from .AbstractScoringLayer import register_layer
from .ComplEx import ComplEx
... |
27,865 | /home/hieuvd/dung_repo/raw/stars_02/Accenture_AmpliGraph/AmpliGraph | /home/hieuvd/dung_repo/raw/stars_02/Accenture_AmpliGraph/AmpliGraph/ampligraph/pretrained_models/pretrained_utils.py | 31,32 | 1,97 | load_pretrained_model | 72,97 | 32,97 | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import logging
from collections import namedtuple
from ampligraph.utils.file_ut... | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import logging
from collections import namedtuple
from ampligraph.utils.file_ut... | assert dataset in ["fb15k-237", "wn18rr", "yago310", "fb15k", "wn18rr"], \
"The dataset you specified is not one of the available ones! Try with one of " \
"the following: ['fb15k-237', 'wn18rr', 'yago310', 'fb15k', 'wn18rr']."
assert scoring_type in ["TransE", "DistMult", "ComplEx", "HolE", "Ro... | """
Function to load a pretrained model.
This function allows downloading and loading one of the AmpliGraph pre-trained
model on benchmark datasets.
Parameters
----------
dataset: str
Specify the dataset on which the pre-trained model was built. The possible
value is one of... | 132 | 812 | 428 | 1,240 | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import logging
from collections import namedtuple
from ampligraph.utils.file_ut... | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import logging
from collections import namedtuple
from ampligraph.utils.file_ut... | |
27,866 | /home/hieuvd/dung_repo/raw/stars_02/Accenture_AmpliGraph/AmpliGraph | /home/hieuvd/dung_repo/raw/stars_02/Accenture_AmpliGraph/AmpliGraph/ampligraph/utils/profiling.py | 50,51 | 1,99 | timing_and_memory | 69,99 | 51,99 | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import tracemalloc
from functools import wraps
from time import time
def get_... | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import tracemalloc
from functools import wraps
from time import time
def get_... |
@wraps(f)
def wrapper(*args, **kwargs):
tracemalloc.start()
mem_before = get_memory_size()
start = time()
result = f(*args, **kwargs)
end = time()
mem_after = get_memory_size()
mem_diff = mem_after - mem_before
print(
"{}: memory befor... | """Decorator to register time and memory used by a function f.
Parameters
----------
f: function
Function for which the time and memory will be measured.
It logs the time and the memory in the dictionary passed inside `'log'`
parameter if provided. Time is logged in seconds, memory in ... | 69 | 641 | 306 | 947 | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import tracemalloc
from functools import wraps
from time import time
def get_... | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import tracemalloc
from functools import wraps
from time import time
def get_... | |
27,867 | /home/hieuvd/dung_repo/raw/stars_02/Accenture_AmpliGraph/AmpliGraph | /home/hieuvd/dung_repo/raw/stars_02/Accenture_AmpliGraph/AmpliGraph/ampligraph/utils/tags.py | 58,59 | 1,88 | deprecated | 78,88 | 59,88 | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import warnings
class experimentalWarning(Warning):
"""Warning that is tr... | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import warnings
class experimentalWarning(Warning):
"""Warning that is tr... |
def mark_deprecated(func):
msg = f"Deprecated! Function: {func.__name__} is deprecated. \
Instead use {kwargs['instead']}."
warnings.warn(DeprecationWarning(msg))
return func
return mark_deprecated
| """
Decorator - a function that accepts another function
and marks it as deprecated, meaning it may be discontinued in
future releases, and is provided only for backward compatibility purposes.
---------------
Example:
>>>@deprecated(instead="module2.another_function")
>>>def a_functio... | 18 | 573 | 79 | 652 | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import warnings
class experimentalWarning(Warning):
"""Warning that is tr... | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import warnings
class experimentalWarning(Warning):
"""Warning that is tr... | |
27,877 | /home/hieuvd/dung_repo/raw/stars_02/Akegarasu_ChatGLM-webui/ChatGLM-webui | /home/hieuvd/dung_repo/raw/stars_02/Akegarasu_ChatGLM-webui/ChatGLM-webui/modules/context.py | 7,8 | 1,99 | parse_codeblock | 8,21 | 8,21 | from typing import Optional, List, Tuple
import json
import os
import time
def parse_codeblock(text):
FILL_FUNC_BODYclass Context:
def __init__(self, history: Optional[List[Tuple[str, str]]] = None):
if history:
self.history = history
else:
self.history = []
self.rh... | from typing import Optional, List, Tuple
import json
import os
import time
def parse_codeblock(text):
FILL_FUNC_BODYclass Context:
def __init__(self, history: Optional[List[Tuple[str, str]]] = None):
if history:
self.history = history
else:
self.history = []
self.rh... | lines = text.split("\n")
for i, line in enumerate(lines):
if "```" in line:
if line != "```":
lines[i] = f'<pre><code class="{lines[i][3:]}">'
else:
lines[i] = '</code></pre>'
else:
if i > 0:
lines[i] = "<br/>" +... | lines = text.split("\n")
for i, line in enumerate(lines):
if "```" in line:
if line != "```":
lines[i] = f'<pre><code class="{lines[i][3:]}">'
else:
lines[i] = '</code></pre>'
else:
if i > 0:
lines[i] = "<br/>" +... | 38 | 880 | 155 | 1,035 | from typing import Optional, List, Tuple
import json
import os
import time
def parse_codeblock(text):
FILL_FUNC_BODYclass Context:
def __init__(self, history: Optional[List[Tuple[str, str]]] = None):
if history:
self.history = history
else:
self.history = []
self.rh... | from typing import Optional, List, Tuple
import json
import os
import time
def parse_codeblock(text):
FILL_FUNC_BODYclass Context:
def __init__(self, history: Optional[List[Tuple[str, str]]] = None):
if history:
self.history = history
else:
self.history = []
self.rh... | |
27,878 | /home/hieuvd/dung_repo/raw/stars_02/Akegarasu_ChatGLM-webui/ChatGLM-webui | /home/hieuvd/dung_repo/raw/stars_02/Akegarasu_ChatGLM-webui/ChatGLM-webui/modules/context.py | 46,47 | 21,98 | clear | Context | 47,50 | 47,50 | class Context:
def __init__(self, history: Optional[List[Tuple[str, str]]] = None):
if history:
self.history = history
else:
self.history = []
self.rh = []
self.max_rounds = 20
def append(self, query, output) -> str:
# c: List[Tuple[str, str]]
... | class Context:
def __init__(self, history: Optional[List[Tuple[str, str]]] = None):
if history:
self.history = history
else:
self.history = []
self.rh = []
self.max_rounds = 20
def append(self, query, output) -> str:
# c: List[Tuple[str, str]]
... | self.history = []
self.rh = []
| self.history = []
self.rh = []
| 6 | 830 | 18 | 848 | from typing import Optional, List, Tuple
import json
import os
import time
def parse_codeblock(text):
lines = text.split("\n")
for i, line in enumerate(lines):
if "```" in line:
if line != "```":
lines[i] = f'<pre><code class="{lines[i][3:]}">'
else:
... | from typing import Optional, List, Tuple
import json
import os
import time
def parse_codeblock(text):
lines = text.split("\n")
for i, line in enumerate(lines):
if "```" in line:
if line != "```":
lines[i] = f'<pre><code class="{lines[i][3:]}">'
else:
... |
27,879 | /home/hieuvd/dung_repo/raw/stars_02/Akegarasu_ChatGLM-webui/ChatGLM-webui | /home/hieuvd/dung_repo/raw/stars_02/Akegarasu_ChatGLM-webui/ChatGLM-webui/modules/device.py | 21,22 | 1,32 | torch_gc | 22,28 | 22,28 | import torch
from modules import options
cpu = torch.device("cpu")
cuda_available = torch.cuda.is_available()
def get_cuda_device():
if options.cmd_opts.device_id is not None:
return f"cuda:{options.cmd_opts.device_id}"
return "cuda"
def get_optimal_device():
if cuda_available:
return ... | import torch
from modules import options
cpu = torch.device("cpu")
cuda_available = torch.cuda.is_available()
def get_cuda_device():
if options.cmd_opts.device_id is not None:
return f"cuda:{options.cmd_opts.device_id}"
return "cuda"
def get_optimal_device():
if cuda_available:
return ... | if cuda_available:
with torch.cuda.device(get_cuda_device()):
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
| if cuda_available:
with torch.cuda.device(get_cuda_device()):
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
| 6 | 194 | 60 | 254 | import torch
from modules import options
cpu = torch.device("cpu")
cuda_available = torch.cuda.is_available()
def get_cuda_device():
if options.cmd_opts.device_id is not None:
return f"cuda:{options.cmd_opts.device_id}"
return "cuda"
def get_optimal_device():
if cuda_available:
return ... | import torch
from modules import options
cpu = torch.device("cpu")
cuda_available = torch.cuda.is_available()
def get_cuda_device():
if options.cmd_opts.device_id is not None:
return f"cuda:{options.cmd_opts.device_id}"
return "cuda"
def get_optimal_device():
if cuda_available:
return ... | |
27,951 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/examples/benchmarks/benchmark_utils.py | 17,24 | 15,42 | save_training_logs | BenchMarkHelper | 24,42 | 24,42 | class BenchMarkHelper:
@classmethod
def save_training_logs(cls,
log_file: str,
embedding_name: str,
model_name: str,
logs: List,
**kwargs: Dict):
FILL_FUNC_BODY | class BenchMarkHelper:
@classmethod
def save_training_logs(cls,
log_file: str,
embedding_name: str,
model_name: str,
logs: List,
**kwargs: Dict):
FILL_FUNC_BODY |
if not os.path.exists(log_file):
data = {}
else:
data = json.loads(open(log_file, 'r').read())
if embedding_name not in data:
data[embedding_name] = {}
data[embedding_name][model_name] = {
'logs': logs,
**kwargs
}
... |
if not os.path.exists(log_file):
data = {}
else:
data = json.loads(open(log_file, 'r').read())
if embedding_name not in data:
data[embedding_name] = {}
data[embedding_name][model_name] = {
'logs': logs,
**kwargs
}
... | 33 | 73 | 151 | 224 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: benchmark_utils.py
# time: 11:05 下午
import os
import json
from typing import List, Dict
class BenchMarkHelper:
@classmethod
def save_training_logs(cls,
log_file: str,
... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: benchmark_utils.py
# time: 11:05 下午
import os
import json
from typing import List, Dict
class BenchMarkHelper:
@classmethod
def save_training_logs(cls,
log_file: str,
... |
27,952 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/embeddings/bert_embedding.py | 22,23 | 16,47 | to_dict | BertEmbedding | 23,27 | 23,27 | class BertEmbedding(TransformerEmbedding):
"""
BertEmbedding is a simple wrapped class of TransformerEmbedding.
If you need load other kind of transformer based language model, please use the TransformerEmbedding.
"""
def to_dict(self) -> Dict[str, Any]:
FILL_FUNC_BODY def __init__(self,
... | class BertEmbedding(TransformerEmbedding):
"""
BertEmbedding is a simple wrapped class of TransformerEmbedding.
If you need load other kind of transformer based language model, please use the TransformerEmbedding.
"""
def to_dict(self) -> Dict[str, Any]:
FILL_FUNC_BODY def __init__(self,
... | info_dic = super(BertEmbedding, self).to_dict()
info_dic['config']['model_folder'] = self.model_folder
return info_dic
| info_dic = super(BertEmbedding, self).to_dict()
info_dic['config']['model_folder'] = self.model_folder
return info_dic
| 9 | 316 | 49 | 365 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: bert_embedding.py
# time: 2:49 下午
import os
from typing import Dict, Any
from kashgari.embeddings.transformer_embedding import TransformerEmbedding
class BertEmbedding(TransformerEmbedding):
"""
BertEmb... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: bert_embedding.py
# time: 2:49 下午
import os
from typing import Dict, Any
from kashgari.embeddings.transformer_embedding import TransformerEmbedding
class BertEmbedding(TransformerEmbedding):
"""
BertEmb... |
27,953 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/macros.py | 24,25 | 19,30 | to_dict | Config | 25,30 | 25,30 | class Config:
def __init__(self) -> None:
self.verbose = False
def to_dict(self) -> Dict:
FILL_FUNC_BODY | class Config:
def __init__(self) -> None:
self.verbose = False
def to_dict(self) -> Dict:
FILL_FUNC_BODY | return {
'verbose': self.verbose
}
| return {
'verbose': self.verbose
}
| 5 | 50 | 24 | 74 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: macros.py
# time: 12:37 下午
import os
from pathlib import Path
from typing import Dict
DATA_PATH = os.path.join(str(Path.home()), '.kashgari')
Path(DATA_PATH).mkdir(exist_ok=True, parents=True)
class Config:
... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: macros.py
# time: 12:37 下午
import os
from pathlib import Path
from typing import Dict
DATA_PATH = os.path.join(str(Path.home()), '.kashgari')
Path(DATA_PATH).mkdir(exist_ok=True, parents=True)
class Config:
... |
27,954 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/metrics/multi_label_classification.py | 21,27 | 1,84 | multi_label_classification_report | 27,82 | 27,82 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: multi_label_classification.py
# time: 6:33 下午
from typing import Dict, Any, TYPE_CHECKING
import numpy as np
from sklearn import metrics
from kashgari.types import MultiLabelClassificationLabelVar
if TYPE_CHECK... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: multi_label_classification.py
# time: 6:33 下午
from typing import Dict, Any, TYPE_CHECKING
import numpy as np
from sklearn import metrics
from kashgari.types import MultiLabelClassificationLabelVar
if TYPE_CHECK... | y_pred_b = binarizer.transform(y_pred)
y_true_b = binarizer.transform(y_true)
report_dic: Dict = {}
details: Dict = {}
rows = []
ps, rs, f1s, s = [], [], [], []
for c_index, c in enumerate(binarizer.classes):
precision = metrics.precision_score(y_true_b[:, c_index], y_pred_b[:, c_i... | y_pred_b = binarizer.transform(y_pred)
y_true_b = binarizer.transform(y_true)
report_dic: Dict = {}
details: Dict = {}
rows = []
ps, rs, f1s, s = [], [], [], []
for c_index, c in enumerate(binarizer.classes):
precision = metrics.precision_score(y_true_b[:, c_index], y_pred_b[:, c_i... | 151 | 237 | 735 | 972 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: multi_label_classification.py
# time: 6:33 下午
from typing import Dict, Any, TYPE_CHECKING
import numpy as np
from sklearn import metrics
from kashgari.types import MultiLabelClassificationLabelVar
if TYPE_CHECK... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: multi_label_classification.py
# time: 6:33 下午
from typing import Dict, Any, TYPE_CHECKING
import numpy as np
from sklearn import metrics
from kashgari.types import MultiLabelClassificationLabelVar
if TYPE_CHECK... | |
27,956 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/processors/abc_processor.py | 79,85 | 19,88 | inverse_transform | ABCProcessor | 85,88 | 85,88 | class ABCProcessor(ABC):
def to_dict(self) -> Dict[str, Any]:
return {
'config': {
'token_pad': self.token_pad,
'token_unk': self.token_unk,
'token_bos': self.token_bos,
'token_eos': self.token_eos,
'vocab2idx': self... | class ABCProcessor(ABC):
def to_dict(self) -> Dict[str, Any]:
return {
'config': {
'token_pad': self.token_pad,
'token_unk': self.token_unk,
'token_bos': self.token_bos,
'token_eos': self.token_eos,
'vocab2idx': self... | raise NotImplementedError
| raise NotImplementedError
| 2 | 769 | 13 | 782 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: abs_processor.py
# time: 2:53 下午
from abc import ABC
from typing import Dict, List, Optional, Any, Tuple
import numpy as np
from kashgari.generators import CorpusGenerator
from kashgari.types import TextSamplesV... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: abs_processor.py
# time: 2:53 下午
from abc import ABC
from typing import Dict, List, Optional, Any, Tuple
import numpy as np
from kashgari.generators import CorpusGenerator
from kashgari.types import TextSamplesV... |
27,957 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/processors/class_processor.py | 37,39 | 22,100 | build_vocab_generator | ClassificationProcessor | 39,68 | 39,68 | class ClassificationProcessor(ABCProcessor):
def to_dict(self) -> Dict[str, Any]:
data = super(ClassificationProcessor, self).to_dict()
data['config']['multi_label'] = self.multi_label
return data
def __init__(self,
multi_label: bool = False,
**kwargs:... | class ClassificationProcessor(ABCProcessor):
def to_dict(self) -> Dict[str, Any]:
data = super(ClassificationProcessor, self).to_dict()
data['config']['multi_label'] = self.multi_label
return data
def __init__(self,
multi_label: bool = False,
**kwargs:... | from kashgari.utils import MultiLabelBinarizer
if self.vocab2idx:
return
vocab2idx: Dict[str, int] = {}
token2count: Dict[str, int] = {}
for generator in generators:
if self.multi_label:
for _, label in tqdm.tqdm(generator, desc="Preparing... | from kashgari.utils import MultiLabelBinarizer
if self.vocab2idx:
return
vocab2idx: Dict[str, int] = {}
token2count: Dict[str, int] = {}
for generator in generators:
if self.multi_label:
for _, label in tqdm.tqdm(generator, desc="Preparing... | 102 | 540 | 401 | 941 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: label_processor.py
# time: 2:53 下午
import collections
import operator
from typing import List, Union, Dict, Optional, Any, Tuple
import numpy as np
import tqdm
from kashgari.generators import CorpusGenerator
fro... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: label_processor.py
# time: 2:53 下午
import collections
import operator
from typing import List, Union, Dict, Optional, Any, Tuple
import numpy as np
import tqdm
from kashgari.generators import CorpusGenerator
fro... |
27,958 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/processors/tools.py | 18,19 | 1,35 | load_processors_from_model | 19,31 | 19,31 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: tools.py
# time: 11:24 上午
import json
import os
from typing import Tuple
from kashgari.processors.abc_processor import ABCProcessor
from kashgari.utils.serialize import load_data_object
def load_processors_from... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: tools.py
# time: 11:24 上午
import json
import os
from typing import Tuple
from kashgari.processors.abc_processor import ABCProcessor
from kashgari.utils.serialize import load_data_object
def load_processors_from... | with open(os.path.join(model_path, 'model_config.json'), 'r') as f:
model_config = json.loads(f.read())
text_processor: ABCProcessor = load_data_object(model_config['text_processor'])
label_processor: ABCProcessor = load_data_object(model_config['label_processor'])
sequence_length_f... | with open(os.path.join(model_path, 'model_config.json'), 'r') as f:
model_config = json.loads(f.read())
text_processor: ABCProcessor = load_data_object(model_config['text_processor'])
label_processor: ABCProcessor = load_data_object(model_config['label_processor'])
sequence_length_f... | 30 | 231 | 196 | 427 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: tools.py
# time: 11:24 上午
import json
import os
from typing import Tuple
from kashgari.processors.abc_processor import ABCProcessor
from kashgari.utils.serialize import load_data_object
def load_processors_from... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: tools.py
# time: 11:24 上午
import json
import os
from typing import Tuple
from kashgari.processors.abc_processor import ABCProcessor
from kashgari.utils.serialize import load_data_object
def load_processors_from... | |
27,959 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/tokenizers/base_tokenizer.py | 18,19 | 13,28 | tokenize | Tokenizer | 27,28 | 19,28 | class Tokenizer:
"""
Abstract base class for all implemented tokenizer.
"""
def tokenize(self, text: str) -> List[str]:
FILL_FUNC_BODY | class Tokenizer:
"""
Abstract base class for all implemented tokenizer.
"""
def tokenize(self, text: str) -> List[str]:
"""
Tokenize text into token sequence
Args:
text: target text sample
Returns:
List of tokens in this sample
"""
FILL_F... | return text.split(' ')
| """
Tokenize text into token sequence
Args:
text: target text sample
Returns:
List of tokens in this sample
"""
return text.split(' ')
| 3 | 92 | 10 | 102 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: base_tokenizer.py
# time: 11:24 上午
from typing import List
class Tokenizer:
"""
Abstract base class for all implemented tokenizer.
"""
def tokenize(self, text: str) -> List[str]:
FILL_FUNC_BODY | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: base_tokenizer.py
# time: 11:24 上午
from typing import List
class Tokenizer:
"""
Abstract base class for all implemented tokenizer.
"""
def tokenize(self, text: str) -> List[str]:
"""
... |
27,960 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/tokenizers/bert_tokenizer.py | 84,85 | 25,156 | _tokenize | BertTokenizer | 85,108 | 85,108 | class BertTokenizer(Tokenizer):
"""
Bert Like Tokenizer, ref: https://github.com/CyberZHG/keras-bert/blob/master/keras_bert/tokenizer.py
"""
def __init__(self,
*,
token_dict: Optional[Dict[str, int]] = None,
token_cls: str = TOKEN_CLS,
... | class BertTokenizer(Tokenizer):
"""
Bert Like Tokenizer, ref: https://github.com/CyberZHG/keras-bert/blob/master/keras_bert/tokenizer.py
"""
def __init__(self,
*,
token_dict: Optional[Dict[str, int]] = None,
token_cls: str = TOKEN_CLS,
... | if not self._cased:
text = unicodedata.normalize('NFD', text)
text = ''.join([ch for ch in text if unicodedata.category(ch) != 'Mn'])
text = text.lower()
spaced = ''
for ch in text:
if self._is_punctuation(ch) or self._is_cjk_character(ch):
... | if not self._cased:
text = unicodedata.normalize('NFD', text)
text = ''.join([ch for ch in text if unicodedata.category(ch) != 'Mn'])
text = text.lower()
spaced = ''
for ch in text:
if self._is_punctuation(ch) or self._is_cjk_character(ch):
... | 82 | 1,171 | 266 | 1,437 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: bert_tokenizer.py
# time: 11:33 上午
# flake8: noqa: E127
import codecs
import unicodedata
from typing import List, Optional, Dict
from kashgari.tokenizers.base_tokenizer import Tokenizer
TOKEN_PAD = '' # Token ... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: bert_tokenizer.py
# time: 11:33 上午
# flake8: noqa: E127
import codecs
import unicodedata
from typing import List, Optional, Dict
from kashgari.tokenizers.base_tokenizer import Tokenizer
TOKEN_PAD = '' # Token ... |
27,961 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/tokenizers/jieba_tokenizer.py | 27,28 | 15,38 | tokenize | JiebaTokenizer | 36,38 | 28,38 | class JiebaTokenizer(Tokenizer):
"""
Jieba tokenizer
"""
def __init__(self) -> None:
try:
import jieba
self._jieba = jieba
except ModuleNotFoundError:
raise ModuleNotFoundError("Jieba module not found, please install use `pip install jieba`")
def... | class JiebaTokenizer(Tokenizer):
"""
Jieba tokenizer
"""
def __init__(self) -> None:
try:
import jieba
self._jieba = jieba
except ModuleNotFoundError:
raise ModuleNotFoundError("Jieba module not found, please install use `pip install jieba`")
def... |
return list(self._jieba.cut(text, **kwargs))
| """
Tokenize text into token sequence
Args:
text: target text sample
Returns:
List of tokens in this sample
"""
return list(self._jieba.cut(text, **kwargs))
| 3 | 164 | 21 | 185 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: jieba_tokenizer.py
# time: 11:54 上午
from typing import List, Any
from kashgari.tokenizers.base_tokenizer import Tokenizer
class JiebaTokenizer(Tokenizer):
"""
Jieba tokenizer
"""
def __init__(s... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: jieba_tokenizer.py
# time: 11:54 上午
from typing import List, Any
from kashgari.tokenizers.base_tokenizer import Tokenizer
class JiebaTokenizer(Tokenizer):
"""
Jieba tokenizer
"""
def __init__(s... |
27,962 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/utils/data.py | 31,33 | 1,50 | unison_shuffled_copies | 42,50 | 33,50 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: data.py
# time: 11:22 上午
import random
from typing import List, Union, TypeVar, Tuple
import numpy as np
T = TypeVar("T")
def get_list_subset(target: List[T], index_list: List[int]) -> List[T]:
"""
Get... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: data.py
# time: 11:22 上午
import random
from typing import List, Union, TypeVar, Tuple
import numpy as np
T = TypeVar("T")
def get_list_subset(target: List[T], index_list: List[int]) -> List[T]:
"""
Get... | data_type = type(a)
assert len(a) == len(b)
c = list(zip(a, b))
random.shuffle(c)
a, b = zip(*c)
if data_type == np.ndarray:
return np.array(a), np.array(b)
return list(a), list(b)
| """
Union shuffle two arrays
Args:
a:
b:
Returns:
"""
data_type = type(a)
assert len(a) == len(b)
c = list(zip(a, b))
random.shuffle(c)
a, b = zip(*c)
if data_type == np.ndarray:
return np.array(a), np.array(b)
return list(a), list(b)
| 26 | 287 | 99 | 386 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: data.py
# time: 11:22 上午
import random
from typing import List, Union, TypeVar, Tuple
import numpy as np
T = TypeVar("T")
def get_list_subset(target: List[T], index_list: List[int]) -> List[T]:
"""
Get... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: data.py
# time: 11:22 上午
import random
from typing import List, Union, TypeVar, Tuple
import numpy as np
T = TypeVar("T")
def get_list_subset(target: List[T], index_list: List[int]) -> List[T]:
"""
Get... | |
27,963 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/utils/model.py | 19,24 | 1,53 | convert_to_saved_model | 37,51 | 24,51 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: model.py
# time: 10:57 上午
import json
import os
import pathlib
import time
from typing import Union, Any
from kashgari.tasks.abs_task_model import ABCTaskModel
def convert_to_saved_model(model: ABCTaskModel,
... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: model.py
# time: 10:57 上午
import json
import os
import pathlib
import time
from typing import Union, Any
from kashgari.tasks.abs_task_model import ABCTaskModel
def convert_to_saved_model(model: ABCTaskModel,
... | if not isinstance(model, ABCTaskModel):
raise ValueError("Only supports the classification model and labeling model")
if version is None:
version = round(time.time())
export_path = os.path.join(model_path, str(version))
pathlib.Path(export_path).mkdir(exist_ok=True, parents=True)
mo... | """
Export model for tensorflow serving
Args:
model: Target model.
model_path: The path to which the SavedModel will be stored.
version: The model version code, default timestamp
signatures: Signatures to save with the SavedModel. Applicable to the
'tf' format onl... | 40 | 326 | 203 | 529 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: model.py
# time: 10:57 上午
import json
import os
import pathlib
import time
from typing import Union, Any
from kashgari.tasks.abs_task_model import ABCTaskModel
def convert_to_saved_model(model: ABCTaskModel,
... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: model.py
# time: 10:57 上午
import json
import os
import pathlib
import time
from typing import Union, Any
from kashgari.tasks.abs_task_model import ABCTaskModel
def convert_to_saved_model(model: ABCTaskModel,
... | |
27,964 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/utils/multi_label.py | 34,35 | 18,44 | inverse_transform | MultiLabelBinarizer | 35,44 | 35,44 | class MultiLabelBinarizer:
def __init__(self, vocab2idx: Dict[str, int]):
self.vocab2idx = vocab2idx
self.idx2vocab = dict([(v, k) for k, v in vocab2idx.items()])
@property
def classes(self) -> List[str]:
return list(self.idx2vocab.values())
def transform(self, samples: MultiLa... | class MultiLabelBinarizer:
def __init__(self, vocab2idx: Dict[str, int]):
self.vocab2idx = vocab2idx
self.idx2vocab = dict([(v, k) for k, v in vocab2idx.items()])
@property
def classes(self) -> List[str]:
return list(self.idx2vocab.values())
def transform(self, samples: MultiLa... | data = []
for sample in preds:
x = []
for label_x in np.where(sample >= threshold)[0]:
x.append(self.idx2vocab[label_x])
data.append(x)
return data
| data = []
for sample in preds:
x = []
for label_x in np.where(sample >= threshold)[0]:
x.append(self.idx2vocab[label_x])
data.append(x)
return data
| 20 | 245 | 76 | 321 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: multi_label.py
# time: 11:23 上午
from typing import List, Dict
import numpy as np
from kashgari.types import MultiLabelClassificationLabelVar
class MultiLabelBinarizer:
def __init__(self, vocab2idx: Dict[s... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: multi_label.py
# time: 11:23 上午
from typing import List, Dict
import numpy as np
from kashgari.types import MultiLabelClassificationLabelVar
class MultiLabelBinarizer:
def __init__(self, vocab2idx: Dict[s... |
27,965 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/kashgari/utils/serialize.py | 14,17 | 1,43 | load_data_object | 27,41 | 17,41 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: serialize.py
# time: 11:23 上午
import pydoc
from typing import Dict, Any
def load_data_object(data: Dict,
custom_objects: Dict = None,
**kwargs: Dict) -> Any:
FILL_FUNC_B... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: serialize.py
# time: 11:23 上午
import pydoc
from typing import Dict, Any
def load_data_object(data: Dict,
custom_objects: Dict = None,
**kwargs: Dict) -> Any:
"""
... | if custom_objects is None:
custom_objects = {}
if data['__class_name__'] in custom_objects:
obj: Any = custom_objects[data['__class_name__']](**data['config'], **kwargs)
else:
module_name = f"{data['__module__']}.{data['__class_name__']}"
obj: Any = pydoc.locate(module_name)... | """
Load Object From Dict
Args:
data:
custom_objects:
**kwargs:
Returns:
"""
if custom_objects is None:
custom_objects = {}
if data['__class_name__'] in custom_objects:
obj: Any = custom_objects[data['__class_name__']](**data['config'], **kwargs)
... | 34 | 178 | 171 | 349 | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: serialize.py
# time: 11:23 上午
import pydoc
from typing import Dict, Any
def load_data_object(data: Dict,
custom_objects: Dict = None,
**kwargs: Dict) -> Any:
FILL_FUNC_B... | # encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: serialize.py
# time: 11:23 上午
import pydoc
from typing import Dict, Any
def load_data_object(data: Dict,
custom_objects: Dict = None,
**kwargs: Dict) -> Any:
"""
... | |
27,966 | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari | /home/hieuvd/dung_repo/raw/stars_02/BrikerMan_Kashgari/Kashgari/setup.py | 29,30 | 1,83 | find_version | 30,38 | 30,38 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: BrikerMan
@contact: eliyar917@gmail.com
@blog: https://eliyar.biz
@version: 1.0
@license: Apache Licence
@file: setup.py
@time: 2019-01-24 16:42
"""
import codecs
import os
import pathlib
import re
from setuptools import find_packages, setup
HERE = pathlib.Path(_... | #!/usr/bin/env python
# encoding: utf-8
"""
@author: BrikerMan
@contact: eliyar917@gmail.com
@blog: https://eliyar.biz
@version: 1.0
@license: Apache Licence
@file: setup.py
@time: 2019-01-24 16:42
"""
import codecs
import os
import pathlib
import re
from setuptools import find_packages, setup
HERE = pathlib.Path(_... | version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
| version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
| 20 | 724 | 92 | 816 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: BrikerMan
@contact: eliyar917@gmail.com
@blog: https://eliyar.biz
@version: 1.0
@license: Apache Licence
@file: setup.py
@time: 2019-01-24 16:42
"""
import codecs
import os
import pathlib
import re
from setuptools import find_packages, setup
HERE = pathlib.Path(_... | #!/usr/bin/env python
# encoding: utf-8
"""
@author: BrikerMan
@contact: eliyar917@gmail.com
@blog: https://eliyar.biz
@version: 1.0
@license: Apache Licence
@file: setup.py
@time: 2019-01-24 16:42
"""
import codecs
import os
import pathlib
import re
from setuptools import find_packages, setup
HERE = pathlib.Path(_... | |
28,025 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/alpaca/sft_alpaca.py | 35,36 | 1,103 | main | 36,93 | 36,93 | import json
import os
from argparse import ArgumentParser
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_sft_config
def get_positive_score(scores):
"Extract value associated with a positive se... | import json
import os
from argparse import ArgumentParser
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_sft_config
def get_positive_score(scores):
"Extract value associated with a positive se... | config = default_sft_config()
config = config.evolve(
train=dict(
total_steps=2400,
batch_size=4,
seq_length=1024,
),
model=dict(
model_path=model_name,
),
tokenizer=dict(
tokenizer_path=model_name,
),
... | config = default_sft_config()
config = config.evolve(
train=dict(
total_steps=2400,
batch_size=4,
seq_length=1024,
),
model=dict(
model_path=model_name,
),
tokenizer=dict(
tokenizer_path=model_name,
),
... | 128 | 531 | 700 | 1,231 | import json
import os
from argparse import ArgumentParser
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_sft_config
def get_positive_score(scores):
"Extract value associated with a positive se... | import json
import os
from argparse import ArgumentParser
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_sft_config
def get_positive_score(scores):
"Extract value associated with a positive se... | |
28,026 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/architext.py | 30,31 | 1,38 | main | 31,36 | 31,36 | # Toy example of optimizing textual interior designs to output the least number of rooms
# Also see https://architext.design/
import trlx
from trlx.data.default_configs import default_ppo_config
def reward_fn(samples, **kwargs):
"Gives a negative count of rooms for each sample"
return [-sample.count(":") for ... | # Toy example of optimizing textual interior designs to output the least number of rooms
# Also see https://architext.design/
import trlx
from trlx.data.default_configs import default_ppo_config
def reward_fn(samples, **kwargs):
"Gives a negative count of rooms for each sample"
return [-sample.count(":") for ... | config = default_ppo_config()
trlx.train(model_path="architext/gptj-162M", reward_fn=reward_fn, prompts=prompts, config=config)
| config = default_ppo_config()
trlx.train(model_path="architext/gptj-162M", reward_fn=reward_fn, prompts=prompts, config=config)
| 7 | 388 | 65 | 453 | # Toy example of optimizing textual interior designs to output the least number of rooms
# Also see https://architext.design/
import trlx
from trlx.data.default_configs import default_ppo_config
def reward_fn(samples, **kwargs):
"Gives a negative count of rooms for each sample"
return [-sample.count(":") for ... | # Toy example of optimizing textual interior designs to output the least number of rooms
# Also see https://architext.design/
import trlx
from trlx.data.default_configs import default_ppo_config
def reward_fn(samples, **kwargs):
"Gives a negative count of rooms for each sample"
return [-sample.count(":") for ... | |
28,028 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/experiments/grounded_program_synthesis/lang.py | 315,316 | 300,339 | sample_production | Sampler | 316,339 | 316,339 | class Sampler:
def __init__(
self,
max_sample_length: int = 5,
code_sep: str = ";",
interpreter_sep: str = "->",
):
self.max_sample_length = max_sample_length
self.parser = Interpreter()
self.production_list = list_manip_dsl
self.production_idt = [... | class Sampler:
def __init__(
self,
max_sample_length: int = 5,
code_sep: str = ";",
interpreter_sep: str = "->",
):
self.max_sample_length = max_sample_length
self.parser = Interpreter()
self.production_list = list_manip_dsl
self.production_idt = [... | init_flag = True
hash_functions = []
if gen_length == None:
gen_length = self.max_sample_length
for ind in range(gen_length):
if init_flag:
random_chosen_function = random.choice(self.production_idt)
generated_function = self.produ... | init_flag = True
hash_functions = []
if gen_length == None:
gen_length = self.max_sample_length
for ind in range(gen_length):
if init_flag:
random_chosen_function = random.choice(self.production_idt)
generated_function = self.produ... | 46 | 188 | 237 | 425 | # flake8: noqa
import copy
import json
import random
from pathlib import Path
from pprint import pprint
from tqdm import tqdm
from transformers import AutoTokenizer
def init_random_input(len_range: int = 5, value_gen=5) -> list:
len_gen = random.randint(2, len_range + 1)
value_range = list(range(-value_gen, ... | # flake8: noqa
import copy
import json
import random
from pathlib import Path
from pprint import pprint
from tqdm import tqdm
from transformers import AutoTokenizer
def init_random_input(len_range: int = 5, value_gen=5) -> list:
len_gen = random.randint(2, len_range + 1)
value_range = list(range(-value_gen, ... |
28,029 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/hh/ilql_hh.py | 83,84 | 1,106 | main | 84,103 | 84,103 | import json
import os
import sys
from itertools import islice
from datasets import load_dataset
from ppo_hh import create_reward_fn
import trlx
from trlx.data.default_configs import (
ILQLConfig,
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
def... | import json
import os
import sys
from itertools import islice
from datasets import load_dataset
from ppo_hh import create_reward_fn
import trlx
from trlx.data.default_configs import (
ILQLConfig,
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
def... | config = TRLConfig.update(default_config, hparams)
dataset = load_dataset("Dahoas/full-hh-rlhf").map(preprocess)
prompts_outputs = sum(dataset["train"]["prompt_output"], [])
rewards = sum(dataset["train"]["reward"], [])
eval_prompts = [{"prompt": x["prompt"], "original_output": x["chosen"]} for x ... | config = TRLConfig.update(default_config, hparams)
dataset = load_dataset("Dahoas/full-hh-rlhf").map(preprocess)
prompts_outputs = sum(dataset["train"]["prompt_output"], [])
rewards = sum(dataset["train"]["reward"], [])
eval_prompts = [{"prompt": x["prompt"], "original_output": x["chosen"]} for x ... | 43 | 1,173 | 260 | 1,433 | import json
import os
import sys
from itertools import islice
from datasets import load_dataset
from ppo_hh import create_reward_fn
import trlx
from trlx.data.default_configs import (
ILQLConfig,
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
def... | import json
import os
import sys
from itertools import islice
from datasets import load_dataset
from ppo_hh import create_reward_fn
import trlx
from trlx.data.default_configs import (
ILQLConfig,
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
def... | |
28,030 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/hh/sft_hh.py | 46,47 | 1,64 | main | 47,61 | 47,61 | import json
import sys
from datasets import load_dataset
from ppo_hh import create_reward_fn
import trlx
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
SFTConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
default_config = TRLConfig(
train=Train... | import json
import sys
from datasets import load_dataset
from ppo_hh import create_reward_fn
import trlx
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
SFTConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
default_config = TRLConfig(
train=Train... | config = TRLConfig.update(default_config, hparams)
dataset = load_dataset("Dahoas/full-hh-rlhf").map(preprocess)
reward_fn = create_reward_fn()
trlx.train(
config=config,
samples=dataset["train"]["chosen_sample"],
eval_prompts=dataset["test"]["prompt"][:280],
metric_fn=... | config = TRLConfig.update(default_config, hparams)
dataset = load_dataset("Dahoas/full-hh-rlhf").map(preprocess)
reward_fn = create_reward_fn()
trlx.train(
config=config,
samples=dataset["train"]["chosen_sample"],
eval_prompts=dataset["test"]["prompt"][:280],
metric_fn=... | 23 | 572 | 174 | 746 | import json
import sys
from datasets import load_dataset
from ppo_hh import create_reward_fn
import trlx
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
SFTConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
default_config = TRLConfig(
train=Train... | import json
import sys
from datasets import load_dataset
from ppo_hh import create_reward_fn
import trlx
from trlx.data.default_configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
SFTConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
default_config = TRLConfig(
train=Train... | |
28,031 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/ilql_sentiments.py | 18,19 | 1,49 | main | 19,46 | 19,46 | import json
import os
import sys
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_ilql_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's ... | import json
import os
import sys
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_ilql_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's ... | # Merge sweep config with default config if given
config = TRLConfig.update(default_ilql_config().to_dict(), hparams)
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra/distilbert-imdb",
top_k=2,
truncation=True,
batch_size=256,
device=0 if int(os.enviro... | # Merge sweep config with default config if given
config = TRLConfig.update(default_ilql_config().to_dict(), hparams)
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra/distilbert-imdb",
top_k=2,
truncation=True,
batch_size=256,
device=0 if int(os.enviro... | 63 | 182 | 310 | 492 | import json
import os
import sys
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_ilql_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's ... | import json
import os
import sys
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, default_ilql_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's ... | |
28,032 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/ilql_sentiments_t5.py | 91,92 | 1,141 | main | 92,139 | 92,139 | import os
from typing import Dict, List
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
import trlx
from trlx.data.configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
from trlx.models.m... | import os
from typing import Dict, List
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
import trlx
from trlx.data.configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
from trlx.models.m... | config = TRLConfig.update(default_config, hparams)
def metric_fn(samples: List[str], **kwargs) -> Dict[str, List[float]]:
sentiments = list(map(get_positive_score, sentiment_fn(samples)))
return dict(sentiments=sentiments)
sentiment_fn = pipeline(
"sentiment-analysis",
"lvw... | config = TRLConfig.update(default_config, hparams)
def metric_fn(samples: List[str], **kwargs) -> Dict[str, List[float]]:
sentiments = list(map(get_positive_score, sentiment_fn(samples)))
return dict(sentiments=sentiments)
sentiment_fn = pipeline(
"sentiment-analysis",
"lvw... | 109 | 811 | 601 | 1,412 | import os
from typing import Dict, List
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
import trlx
from trlx.data.configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
from trlx.models.m... | import os
from typing import Dict, List
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
import trlx
from trlx.data.configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
from trlx.models.m... | |
28,033 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/nemo_ilql_sentiments.py | 18,19 | 1,67 | main | 19,65 | 19,65 | from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import default_ilql_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's output"
return dict(map(lambda x: tuple(... | from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import default_ilql_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's output"
return dict(map(lambda x: tuple(... | # Merge sweep config with default config if given
config = default_config.evolve(
train=dict(
seq_length=1024,
batch_size=512,
total_steps=200,
trainer="NeMoILQLTrainer",
trainer_kwargs=dict(
pretrained_model=None,
... | # Merge sweep config with default config if given
config = default_config.evolve(
train=dict(
seq_length=1024,
batch_size=512,
total_steps=200,
trainer="NeMoILQLTrainer",
trainer_kwargs=dict(
pretrained_model=None,
... | 75 | 151 | 443 | 594 | from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import default_ilql_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's output"
return dict(map(lambda x: tuple(... | from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import default_ilql_config
def get_positive_score(scores):
"Extract value associated with a positive sentiment from pipeline's output"
return dict(map(lambda x: tuple(... | |
28,034 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/nemo_ppo_sentiments.py | 26,27 | 1,119 | main | 27,116 | 27,116 | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
from datasets import load_dataset
from transformers import DistilBertForSequenceClassification, pipeline
import trlx
from trlx.data.default_config... | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
from datasets import load_dataset
from transformers import DistilBertForSequenceClassification, pipeline
import trlx
from trlx.data.default_config... | # Merge sweep config with default config if given
default_config = TRLConfig.update(default_ppo_config().to_dict(), hparams)
cfg_name = os.environ.get("NEMO_CONFIG", "1.3B")
if cfg_name == "1.3B":
nemo_config = default_nemo_1_3b_config()
elif cfg_name == "2B":
nemo_config = default_... | # Merge sweep config with default config if given
default_config = TRLConfig.update(default_ppo_config().to_dict(), hparams)
cfg_name = os.environ.get("NEMO_CONFIG", "1.3B")
if cfg_name == "1.3B":
nemo_config = default_nemo_1_3b_config()
elif cfg_name == "2B":
nemo_config = default_... | 171 | 262 | 1,135 | 1,397 | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
from datasets import load_dataset
from transformers import DistilBertForSequenceClassification, pipeline
import trlx
from trlx.data.default_config... | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
from datasets import load_dataset
from transformers import DistilBertForSequenceClassification, pipeline
import trlx
from trlx.data.default_config... | |
28,035 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/nemo_sft_sentiments.py | 21,22 | 1,76 | main | 22,74 | 22,74 | import os
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import (
TRLConfig,
default_nemo_1_3b_config,
default_nemo_20b_config,
default_sft_config,
)
def get_positive_score(scores):
"Extract value assoc... | import os
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import (
TRLConfig,
default_nemo_1_3b_config,
default_nemo_20b_config,
default_sft_config,
)
def get_positive_score(scores):
"Extract value assoc... | # Merge sweep config with default config if given
default_config = TRLConfig.update(default_sft_config(), hparams)
cfg_name = os.environ.get("NEMO_CONFIG", "1.3B")
if cfg_name == "1.3B":
nemo_config = default_nemo_1_3b_config()
elif cfg_name == "20B":
nemo_config = default_nemo_20b... | # Merge sweep config with default config if given
default_config = TRLConfig.update(default_sft_config(), hparams)
cfg_name = os.environ.get("NEMO_CONFIG", "1.3B")
if cfg_name == "1.3B":
nemo_config = default_nemo_1_3b_config()
elif cfg_name == "20B":
nemo_config = default_nemo_20b... | 113 | 181 | 648 | 829 | import os
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import (
TRLConfig,
default_nemo_1_3b_config,
default_nemo_20b_config,
default_sft_config,
)
def get_positive_score(scores):
"Extract value assoc... | import os
from typing import Dict, List
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import (
TRLConfig,
default_nemo_1_3b_config,
default_nemo_20b_config,
default_sft_config,
)
def get_positive_score(scores):
"Extract value assoc... | |
28,036 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/ppo_dense_sentiments.py | 25,26 | 1,76 | main | 26,73 | 26,73 | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, defa... | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, defa... | # Merge sweep config with default config if given
config = TRLConfig.update(default_ppo_config().to_dict(), hparams)
if torch.cuda.is_available():
device = int(os.environ.get("LOCAL_RANK", 0))
else:
device = -1
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra... | # Merge sweep config with default config if given
config = TRLConfig.update(default_ppo_config().to_dict(), hparams)
if torch.cuda.is_available():
device = int(os.environ.get("LOCAL_RANK", 0))
else:
device = -1
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra... | 186 | 244 | 696 | 940 | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, defa... | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, defa... | |
28,037 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/ppo_sentiments.py | 21,22 | 1,58 | main | 22,55 | 22,55 | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, defa... | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, defa... | # Merge sweep config with default config if given
config = TRLConfig.update(default_ppo_config().to_dict(), hparams)
if torch.cuda.is_available():
device = int(os.environ.get("LOCAL_RANK", 0))
else:
device = -1
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra... | # Merge sweep config with default config if given
config = TRLConfig.update(default_ppo_config().to_dict(), hparams)
if torch.cuda.is_available():
device = int(os.environ.get("LOCAL_RANK", 0))
else:
device = -1
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra... | 81 | 207 | 357 | 564 | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, defa... | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import TRLConfig, defa... | |
28,038 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/ppo_sentiments_llama.py | 29,30 | 1,112 | llama_config | 30,75 | 30,75 | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import (
ModelConf... | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import (
ModelConf... | return TRLConfig(
train=TrainConfig(
seq_length=1024,
epochs=100,
total_steps=400,
batch_size=32,
checkpoint_interval=10000,
eval_interval=100,
pipeline="PromptPipeline",
trainer="AcceleratePPOTrainer",
... | return TRLConfig(
train=TrainConfig(
seq_length=1024,
epochs=100,
total_steps=400,
batch_size=32,
checkpoint_interval=10000,
eval_interval=100,
pipeline="PromptPipeline",
trainer="AcceleratePPOTrainer",
... | 53 | 570 | 578 | 1,148 | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import (
ModelConf... | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from transformers import pipeline
import trlx
from trlx.data.default_configs import (
ModelConf... | |
28,039 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/ppo_sentiments_peft.py | 23,24 | 1,68 | main | 24,65 | 24,65 | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from peft import LoraConfig
from peft.utils.config import TaskType
from transformers import pipeline... | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from peft import LoraConfig
from peft.utils.config import TaskType
from transformers import pipeline... | # Merge sweep config with default config if given
config = TRLConfig.update(default_ppo_config().to_dict(), hparams)
if torch.cuda.is_available():
device = int(os.environ.get("LOCAL_RANK", 0))
else:
device = -1
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra... | # Merge sweep config with default config if given
config = TRLConfig.update(default_ppo_config().to_dict(), hparams)
if torch.cuda.is_available():
device = int(os.environ.get("LOCAL_RANK", 0))
else:
device = -1
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra... | 107 | 226 | 455 | 681 | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from peft import LoraConfig
from peft.utils.config import TaskType
from transformers import pipeline... | # Generates positive movie reviews by tuning a pretrained model on IMDB dataset
# with a sentiment reward function
import json
import os
import sys
from typing import List
import torch
from datasets import load_dataset
from peft import LoraConfig
from peft.utils.config import TaskType
from transformers import pipeline... | |
28,040 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/ppo_sentiments_t5.py | 106,107 | 1,174 | main | 107,171 | 107,171 | import json
import os
import sys
from typing import Dict, List
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
import trlx
from trlx.data.configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfi... | import json
import os
import sys
from typing import Dict, List
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
import trlx
from trlx.data.configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfi... | config = TRLConfig.update(default_config, hparams)
def metric_fn(samples: List[str], **kwargs) -> Dict[str, List[float]]:
sentiments = list(map(get_positive_score, sentiment_fn(samples)))
return sentiments
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra/distilbert-i... | config = TRLConfig.update(default_config, hparams)
def metric_fn(samples: List[str], **kwargs) -> Dict[str, List[float]]:
sentiments = list(map(get_positive_score, sentiment_fn(samples)))
return sentiments
sentiment_fn = pipeline(
"sentiment-analysis",
"lvwerra/distilbert-i... | 158 | 951 | 870 | 1,821 | import json
import os
import sys
from typing import Dict, List
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
import trlx
from trlx.data.configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfi... | import json
import os
import sys
from typing import Dict, List
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer, pipeline
import trlx
from trlx.data.configs import (
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfi... | |
28,041 | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx | /home/hieuvd/dung_repo/raw/stars_02/CarperAI_trlx/trlx/examples/randomwalks/ilql_randomwalks.py | 16,17 | 1,70 | main | 17,35 | 17,35 | from transformers import GPT2Config
import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ILQLConfig,
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
def main(hparams):
FILL_FUNC_BODYdefault_con... | from transformers import GPT2Config
import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ILQLConfig,
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
def main(hparams):
FILL_FUNC_BODYdefault_con... | config = TRLConfig.update(default_config, hparams)
metric_fn, eval_prompts, walks, _ = generate_random_walks(seed=config.train.seed)
rewards = metric_fn(walks)["optimality"]
# split each random walk into (starting state, rest of the walk)
walks = [[walk[:1], walk[1:]] for walk in walks]
trlx.t... | config = TRLConfig.update(default_config, hparams)
metric_fn, eval_prompts, walks, _ = generate_random_walks(seed=config.train.seed)
rewards = metric_fn(walks)["optimality"]
# split each random walk into (starting state, rest of the walk)
walks = [[walk[:1], walk[1:]] for walk in walks]
trlx.t... | 47 | 601 | 232 | 833 | from transformers import GPT2Config
import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ILQLConfig,
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
def main(hparams):
FILL_FUNC_BODYdefault_con... | from transformers import GPT2Config
import trlx
from examples.randomwalks import generate_random_walks
from trlx.data.default_configs import (
ILQLConfig,
ModelConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
TrainConfig,
TRLConfig,
)
def main(hparams):
FILL_FUNC_BODYdefault_con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.