repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -0,0 +1,292 @@
+# Copyright 2023 The Wordcab Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Automate module of the Wordcab Transcribe."""
+
+import json
+from typing import List, Optional
+
+import requests
+
+
+def run_api_youtube(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ server_url: Optional[str] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for Youtube videos.
+
+ Args:
+ url (str): URL source of the Youtube video.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: associated words and their timestamps (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ server_url: the URL used to reach out the API.
+
+ Returns:
+ YouTubeResponse
+ """
+ headers = {"accept": "application/json", "Content-Type": "application/json"}
+ params = {"url": url}
+ data = {
+ "alignment": alignment,
+ "diarization": diarization,
+ "source_lang": source_lang,
+ "timestamps": timestamps,
+ "word_timestamps": word_timestamps,
+ }
+
+ if server_url is None:
+ response = requests.post(
+ "http://localhost:5001/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"{server_url}/api/v1/youtube",
+ headers=headers,
+ params=params,
+ data=json.dumps(data),
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[-1]
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_audio_url(
+ url: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: Optional[str] = None,
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio URLs.
+
+ Args:
+ url (str): URL source of the audio file.
+ source_lang: language of the URL source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 90 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ headers = {"accept": "application/json", "content-type": "application/json"}
+
+ params = {"url": url}
+
+ data = {
+ "alignment": alignment,
+ "diarization": diarization,
+ "source_lang": source_lang,
+ "timestamps": timestamps,
+ "word_timestamps": word_timestamps,
+ "dual_channel": dual_channel,
+ }
+ if vocab:
+ data["vocab"] = vocab
+
+ if server_url == "None":
+ response = requests.post(
+ "https://wordcab.com/api/v1/audio-url",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+ else:
+ response = requests.post(
+ f"{server_url}/api/v1/audio-url",
+ headers=headers,
+ params=params,
+ data=data,
+ timeout=timeout,
+ )
+
+ if response.json == 200:
+ r_json = response.json()
+ else:
+ raise ValueError("Unexpected JSON response")
+
+ url_name = url.split("https://")[-1]
+
+ with open(f"{url_name}.json", "w", encoding="utf-8") as f:
+ json.dump(r_json, f, indent=4, ensure_ascii=False)
+
+
+def run_api_audio_file(
+ file: str,
+ source_lang: str = "en",
+ timestamps: str = "s",
+ word_timestamps: bool = False,
+ alignment: bool = False,
+ diarization: bool = False,
+ dual_channel: bool = False,
+ server_url: Optional[str] = None,
+ vocab: Optional[List[str]] = None,
+ timeout: int = 900,
+):
+ """
+ Run API call for audio files.
+
+ Args:
+ file (str): file source of the audio file.
+ source_lang: language of the source (defaulted to English)
+ timestamps: time unit of the timestamps (defaulted to seconds)
+ word_timestamps: whether the timestamps are represented by words (defaulted to False)
+ alignment: re-align timestamps (defaulted to False)
+ diarization: speaker labels for utterances (defaulted to False)
+ dual_channel: defaulted to False
+ server_url: defaulted to string value None
+ vocab: defaulted to empty list
+ timeout: defaulted to 900 seconds (15 minutes)
+
+ Returns:
+ AudioResponse
+ """
+ filepath = file # or any other convertible format by ffmpeg
+ data = {
+ "alignment": alignment,
+ "diarization": diarization,
+ "source_lang": source_lang,
+ "timestamps": timestamps,
+ "word_timestamps": word_timestamps,
+ "dual_channel": dual_channel,
+ }
+ if vocab:
+ data["vocab"] = vocab
+
+ with open(filepath, "rb") as f:
+ files = {"file": f} | ```suggestion
data = {
"alignment": alignment,
"diarization": diarization,
"source_lang": source_lang,
"timestamps": timestamps,
"word_timestamps": word_timestamps,
"dual_channel": dual_channel,
}
if vocab:
data["vocab"] = vocab
with open(file, "rb") as f:
files = {"file": f}
``` |
wordcab-transcribe | github_2023 | python | 94 | Wordcab | chainyo | @@ -14,6 +14,7 @@
"""Utils module of the Wordcab Transcribe."""
import asyncio
import json
+import requests
import math
import re
import subprocess # noqa: S404 | ```suggestion
"""Utils module of the Wordcab Transcribe."""
import asyncio
import json
import math
import re
import subprocess # noqa: S404
``` |
wordcab-transcribe | github_2023 | python | 179 | Wordcab | chainyo | @@ -398,9 +398,12 @@ def __call__(
# )
# if not use_batch and not isinstance(audio, tuple):
- if vocab:
- words = ", ".join(vocab)
- prompt = f"Vocab: {words[:-2]}"
+ if vocab is not None:
+ if isinstance(vocab, list) and len(vocab) > 0 and vocab[0].strip():
+ words = ", ".join(vocab)
+ prompt = f"Vocab: {words.strip()}"
+ else:
+ prompt = None
else:
prompt = None | ```suggestion
if (
vocab is not None
and isinstance(vocab, list)
and len(vocab) > 0
and vocab[0].strip()
):
words = ", ".join(vocab)
prompt = f"Vocab: {words.strip()}"
else:
prompt = None
``` |
wordcab-transcribe | github_2023 | python | 18 | Wordcab | chainyo | @@ -127,6 +130,41 @@ async def download_file_from_youtube(url: str, filename: str) -> str:
return filename + ".wav"
+async def download_audio_file(url: str, filename: str) -> str:
+ """
+ Download an audio file from a URL.
+
+ Args:
+ url (str): URL of the audio file.
+ filename (str): Filename to save the file as.
+
+ Raises:
+ Exception: If the file failed to download.
+
+ Returns:
+ str: Path to the downloaded file.
+ """
+ logger.info(f"Downloading audio file from {url} to {filename}...")
+ async with aiohttp.ClientSession() as session:
+ async with session.get(url) as response:
+ if response.status == 200:
+ content_type = response.headers.get("Content-Type")
+ extension = mimetypes.guess_extension(content_type)
+ logger.info(f"Guessing extension based on MIME type: {extension}")
+ filename = f"{filename}{extension}"
+ logger.info(f"New file name: {filename}")
+ async with aiofiles.open(filename, "wb") as f:
+ while True:
+ chunk = await response.content.read(1024)
+ if not chunk:
+ break
+ await f.write(chunk)
+ else:
+ raise Exception(f"Failed to download file. Status: {response.status}")
+
+ return filename | I added `url_headers` because some signed url can require authentication.
```suggestion
async def download_audio_file(
url: str, filename: str, url_headers: Optional[Dict[str, str]] = None
) -> str:
"""
Download an audio file from a URL.
Args:
url (str): URL of the audio file.
filename (str): Filename to save the file as.
url_headers (Optional[Dict[str, str]]): Headers to send with the request. Defaults to None.
Raises:
Exception: If the file failed to download.
Returns:
str: Path to the downloaded file.
"""
url_headers = url_headers or {}
logger.info(f"Downloading audio file from {url} to {filename}...")
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=url_headers) as response:
if response.status == 200:
content_type = response.headers.get("Content-Type")
extension = mimetypes.guess_extension(content_type)
filename = f"{filename}{extension}"
logger.info(f"New file name: {filename}")
async with aiofiles.open(filename, "wb") as f:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
await f.write(chunk)
else:
raise Exception(f"Failed to download file. Status: {response.status}")
return filename
``` |
wordcab-transcribe | github_2023 | python | 18 | Wordcab | chainyo | @@ -12,15 +12,18 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utils module of the Wordcab Transcribe."""
-
import asyncio
import math
+import mimetypes
import re
import subprocess # noqa: S404
import sys
from pathlib import Path
from typing import List, Optional | ```suggestion
from typing import Dict, List, Optional
``` |
wordcab-transcribe | github_2023 | python | 16 | Wordcab | aleksandr-smechov | @@ -50,6 +51,15 @@
async def startup_event():
"""Startup event handler."""
logger.debug("Starting up...")
+
+ user_platform = retrieve_user_platform()
+ if user_platform != "Ubuntu" or user_platform != "Linux":
+ logger.warning(
+ "You are not running the application on Ubuntu or Linux.\n" | Did you mean MacOS or Linux |
wordcab-transcribe | github_2023 | python | 8 | Wordcab | chainyo | @@ -131,18 +133,20 @@ async def inference_with_audio(
else:
filepath = filename
- utterances = await asr.process_input(
+ raw_utterances = await asr.process_input(
filepath, num_speakers, source_lang, timestamps
)
- utterances = [
- {
- "text": str(utterance["text"]),
- "start": utterance["start"],
- "end": utterance["end"],
- "speaker": int(utterance["speaker"]),
- }
- for utterance in utterances
- ]
+ utterances = []
+ for utterance in raw_utterances:
+ if not is_empty_string(utterance["text"]):
+ utterances.append(
+ {
+ "text": format_punct(utterance["text"]),
+ "start": utterance["start"],
+ "end": utterance["end"],
+ "speaker": int(utterance["speaker"]),
+ }
+ ) | I would keep the list comprehension style for readability.
```suggestion
utterances = [
{
"text": format_punct(utterance["text"]),
"start": utterance["start"],
"end": utterance["end"],
"speaker": int(utterance["speaker"]),
}
for utterance in raw_utterances
if not is_empty_string(utterance["text"])
]
``` |
wordcab-transcribe | github_2023 | python | 8 | Wordcab | chainyo | @@ -187,18 +191,20 @@ async def inference_with_youtube(
filename = f"yt_{shortuuid.ShortUUID().random(length=32)}"
filepath = await download_file_from_youtube(url, filename)
- utterances = await asr.process_input(
+ raw_utterances = await asr.process_input(
filepath, num_speakers, source_lang, timestamps
)
- utterances = [
- {
- "text": str(utterance["text"]),
- "start": utterance["start"],
- "end": utterance["end"],
- "speaker": int(utterance["speaker"]),
- }
- for utterance in utterances
- ]
+ utterances = []
+ for utterance in raw_utterances:
+ if not is_empty_string(utterance["text"]):
+ utterances.append(
+ {
+ "text": format_punct(utterance["text"]),
+ "start": utterance["start"],
+ "end": utterance["end"],
+ "speaker": int(utterance["speaker"]),
+ }
+ ) | Same here:
```suggestion
utterances = [
{
"text": format_punct(utterance["text"]),
"start": utterance["start"],
"end": utterance["end"],
"speaker": int(utterance["speaker"]),
}
for utterance in raw_utterances
if not is_empty_string(utterance["text"])
]
``` |
wordcab-transcribe | github_2023 | python | 8 | Wordcab | chainyo | @@ -139,6 +139,26 @@ def delete_file(filepath: str) -> None:
filepath.unlink()
+def is_empty_string(text):
+ text = text.replace(".", "")
+ text = re.sub(r"\s+", "", text)
+ if text.strip():
+ return False
+ return True
+
+
+def format_punct(text):
+ text = text.replace("...", "") | I think `.maketrans()` could be faster than multiple `.replace()`, but it's probably irrelevant here. |
php-tui | github_2023 | php | 193 | php-tui | dantleech | @@ -65,19 +65,20 @@ public function render(WidgetRenderer $renderer, Widget $widget, Buffer $buffer)
->setStyle($widget->yAxis->style);
}
- foreach ($widget->dataSets as $dataSet) {
- $subBuffer = Buffer::empty($layout->graphArea);
- $renderer->render($renderer, CanvasWidget::default()
+ $widgets = array_map(function (DataSet $dataSet) use ($widget): CanvasWidget {
+ return CanvasWidget::default()
->backgroundColor($widget->style->bg ?? AnsiColor::Reset)
->xBounds($this->resolveBounds($dataSet, $widget->xAxis->bounds, 0))
->yBounds($this->resolveBounds($dataSet, $widget->yAxis->bounds, 1))
->marker($dataSet->marker)
->paint(function (CanvasContext $context) use ($dataSet): void {
$context->draw(PointsShape::new($dataSet->data, $dataSet->style->fg ?? AnsiColor::Reset));
- }), $subBuffer);
- $buffer->putBuffer($layout->graphArea->position, $subBuffer);
+ });
+ }, $widget->dataSets);
- }
+ $subBuffer = Buffer::empty($layout->graphArea);
+ $renderer->render($renderer, CompositeWidget::fromWidgets(...$widgets), $subBuffer);
+ $buffer->putBuffer($layout->graphArea->position, $subBuffer); | not sure this needs a "sub buffer"? the buffer passed to the widget should already be empty |
php-tui | github_2023 | php | 169 | php-tui | dantleech | @@ -8,16 +8,16 @@
final class Modifier
{
- public const NONE = 0b000000000000;
- public const BOLD = 0b000000000001;
- public const DIM = 0b000000000010;
- public const ITALIC = 0b000000000100;
- public const UNDERLINED = 0b000000001000;
- public const SLOWBLINK = 0b000000010000;
- public const RAPIDBLINK = 0b000000100000;
- public const REVERSED = 0b000001000000;
- public const HIDDEN = 0b000010000000;
- public const CROSSEDOUT = 0b000100000000;
+ public const NONE = 0b000000000000;
+ public const BOLD = 0b000000000001;
+ public const DIM = 0b000000000010;
+ public const ITALIC = 0b000000000100;
+ public const UNDERLINED = 0b000000001000;
+ public const SLOWBLINK = 0b000000010000;
+ public const RAPIDBLINK = 0b000000100000;
+ public const REVERSED = 0b000001000000;
+ public const HIDDEN = 0b000010000000;
+ public const CROSSEDOUT = 0b000100000000; | would be nice if these could stay aligned somehow as it's good visual validation |
php-tui | github_2023 | php | 140 | php-tui | dantleech | @@ -0,0 +1,10 @@
+<?php
+
+declare(strict_types=1);
+
+namespace PhpTui\Tui\Model;
+
+interface Parseable
+{
+ public static function parse(string $string): self; | This interface is a bit anaemic (it's about Style but the naming implies anything or everything) and it's role is more of a Parser and not something that can be parsed? - maybe rename to StyleParser with return type Style? |
php-tui | github_2023 | php | 140 | php-tui | dantleech | @@ -80,10 +78,7 @@ public function lorem(): ParagraphWidget
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
return ParagraphWidget::fromText(
- Text::styled(
- $text,
- Style::default()->fg(AnsiColor::DarkGray)
- )
+ Text::parse("<fg=darkgray>{$text}</>") | minor: use `sprintf` instead, maybe there's a CS rule for that :thinking: |
php-tui | github_2023 | php | 140 | php-tui | dantleech | @@ -58,6 +59,13 @@ public static function fromString(string $string): self
], null);
}
+ public static function parse(string $string): self
+ {
+ return self::fromSpans(
+ SpanParser::new()->parse($string) | not related to this PR but I want to make all `fromFoos(` variadics, so should be `fromSpans(...SpanParser::new()->parse($string))` |
php-tui | github_2023 | php | 140 | php-tui | dantleech | @@ -0,0 +1,135 @@
+<?php
+
+declare(strict_types=1);
+
+namespace PhpTui\Tui\Model\Widget;
+
+use PhpTui\Tui\Model\Color;
+use PhpTui\Tui\Model\Color\AnsiColor;
+use PhpTui\Tui\Model\Color\RgbColor;
+use PhpTui\Tui\Model\Modifier;
+use PhpTui\Tui\Model\Style;
+
+final class SpanParser
+{
+ private const OPEN_TAG_REGEX = '[a-z](?:[^\\\\<>]*+ | \\\\.)*';
+ private const CLOSE_TAG_REGEX = '[a-z][^<>]*+';
+
+ /** @var array<Style> */
+ private array $styleStack = []; | maybe avoid state and pass `&$styleStack` in the function calls? |
php-tui | github_2023 | php | 140 | php-tui | dantleech | @@ -0,0 +1,135 @@
+<?php
+
+declare(strict_types=1);
+
+namespace PhpTui\Tui\Model\Widget;
+
+use PhpTui\Tui\Model\Color;
+use PhpTui\Tui\Model\Color\AnsiColor;
+use PhpTui\Tui\Model\Color\RgbColor;
+use PhpTui\Tui\Model\Modifier;
+use PhpTui\Tui\Model\Style;
+
+final class SpanParser | let's make this a subset of the Symfony Console component markup, and add a class comment here with a link to: `https://symfony.com/doc/current/console/coloring.html` |
php-tui | github_2023 | php | 140 | php-tui | dantleech | @@ -0,0 +1,135 @@
+<?php
+
+declare(strict_types=1);
+
+namespace PhpTui\Tui\Model\Widget;
+
+use PhpTui\Tui\Model\Color;
+use PhpTui\Tui\Model\Color\AnsiColor;
+use PhpTui\Tui\Model\Color\RgbColor;
+use PhpTui\Tui\Model\Modifier;
+use PhpTui\Tui\Model\Style;
+
+final class SpanParser
+{
+ private const OPEN_TAG_REGEX = '[a-z](?:[^\\\\<>]*+ | \\\\.)*';
+ private const CLOSE_TAG_REGEX = '[a-z][^<>]*+';
+
+ /** @var array<Style> */
+ private array $styleStack = [];
+
+ public static function new(): self
+ {
+ return new self();
+ }
+
+ /**
+ * @return array<Span>
+ */
+ public function parse(string $input): array
+ {
+ $regex = sprintf('#<((%s) | /(%s)?)>#ix', self::OPEN_TAG_REGEX, self::CLOSE_TAG_REGEX); | in Symfony the delimiter is `;` not space... |
php-tui | github_2023 | php | 140 | php-tui | dantleech | @@ -26,6 +27,22 @@ public static function fromString(string $string): self
}, explode("\n", $string)));
}
+ public static function parse(string $string): self
+ {
+ $placeholder = sprintf('{{new_line_%s}}', microtime(true)); | `uniqid` would be safer than `microtime` |
php-tui | github_2023 | php | 140 | php-tui | dantleech | @@ -0,0 +1,278 @@
+<?php
+
+declare(strict_types=1);
+
+namespace PhpTui\Tui\Tests\Unit\Model\Widget;
+
+use InvalidArgumentException;
+use PhpTui\Tui\Model\Color\AnsiColor;
+use PhpTui\Tui\Model\Color\RgbColor;
+use PhpTui\Tui\Model\Modifier;
+use PhpTui\Tui\Model\Widget\SpanParser;
+use PHPUnit\Framework\TestCase;
+
+class SpanParserTest extends TestCase
+{
+ public function testParseOneTag(): void
+ {
+ $spans = SpanParser::new()->parse('<fg=green bg=blue options=bold,italic>Hello</> World'); | as mentioned previously, to be compatible with Symfony we need this to be delimited with `;` |
php-tui | github_2023 | php | 140 | php-tui | dantleech | @@ -10,6 +10,12 @@
use PhpTui\Tui\Model\Modifier;
use PhpTui\Tui\Model\Style;
+/**
+ * This class is a subset of the Symfony Console component's OutputFormatter class.
+ * It parses strings containing tags into a list of spans. | Technically it's not a subset of the class but a subset of the ... markup? |
php-tui | github_2023 | php | 136 | php-tui | dantleech | @@ -0,0 +1,97 @@
+<?php
+
+declare(strict_types=1);
+
+namespace PhpTui\Tui\Model\Style;
+
+use PhpTui\Tui\Model\AnsiColor;
+use PhpTui\Tui\Model\Color;
+use PhpTui\Tui\Model\Style;
+
+trait InteractsWithBgColor | do we need 3 traits? either something can have a style or it cannot? I would call it `StyleableTrait`. |
php-tui | github_2023 | php | 131 | php-tui | dantleech | @@ -41,7 +41,7 @@ public function toStyledGraphemes(Style $baseStyle): array
return array_map(function (string $grapheme) use ($baseStyle) {
return new StyledGrapheme(
symbol: $grapheme,
- style: $baseStyle->patch($this->style),
+ style: $this->style->patch($baseStyle), | note the original is faithful to Ratatui: https://github.com/ratatui-org/ratatui/blob/9f371000968044e09545d66068c4ed4ea4b35d8a/src/text/span.rs#L141
opened a PR on your PR https://github.com/KennedyTedesco/php-tui/pull/1 |
php-tui | github_2023 | php | 104 | php-tui | dantleech | @@ -25,10 +25,11 @@ public function testEmpty(): void
public function testFilled(): void
{
- $buffer = Buffer::filled(Area::fromScalars(0, 0, 10, 10), Cell::fromChar('X'));
+ $cell = Cell::fromChar('X');
+ $buffer = Buffer::filled(Area::fromScalars(0, 0, 10, 10), $cell);
self::assertCount(100, $buffer);
self::assertEquals(array_fill(0, 100, Cell::fromChar('X')), $buffer->content());
- self::assertNotSame($buffer->get(Position::at(0, 0))->modifier, $buffer->get(Position::at(1, 1))->modifier, 'cells are propertly cloned!');
+ self::assertNotSame(spl_object_id($cell), spl_object_id($buffer->get(Position::at(1, 1))), 'cells are propertly cloned!'); | Same is an identity check anyway, so `spl_object_id` is redundant here I think |
php-tui | github_2023 | php | 78 | php-tui | dantleech | @@ -103,12 +97,10 @@ private static function renderChar(
}
}
- $maxX = null;
foreach ($points as $point) {
- if (null === $point) {
- continue;
+ if (null !== $point) { | this was an "early continue" and is intentional, it's a guard condition. |
php-tui | github_2023 | php | 66 | php-tui | dantleech | @@ -53,16 +53,18 @@ public function advance(): void
*/
public function parseLine(): string
{
- $taken = $this->takeWhile(fn (?string $token) => $token !== "\n");
+ $taken = $this->takeWhile(
+ static fn (string $token): bool => $token !== PHP_EOL | `PHP_EOL` is platform dependent IIRC. really we should be checking for any type of new line `\n`, `\r`, `\r\n` or whatever, but otherwise happy to keep it with `"\n"` |
php-tui | github_2023 | php | 66 | php-tui | dantleech | @@ -0,0 +1,26 @@
+<?php
+
+namespace PhpTui\Bdf\Tests\Benchmark;
+
+use RuntimeException;
+use PhpTui\BDF\BdfParser;
+use PhpBench\Attributes\Iterations;
+use PhpBench\Attributes\Revs;
+
+#[Iterations(10)]
+#[Revs(25)]
+final class BdfParserBench
+{
+ public function benchParseRealFont(): void
+ {
+ $contents = file_get_contents(__DIR__ . '/../../fonts/6x10.bdf');
+
+ if (false === $contents) {
+ throw new RuntimeException(
+ 'Could not read file'
+ );
+ }
+
+ (new BdfParser())->parse($contents); | it won't make much difference, but it's better to do any setup _outside_ of the `bench` method as it can muddy the results (we're not benchmarking `file_get_contents`). The simplest way is to do it in the constructor (you can also add custom `setUp` methods but `__construct` is fine |
php-tui | github_2023 | php | 65 | php-tui | dantleech | @@ -66,4 +75,13 @@ public function paint(Position $position, Color $color): void
$this->colors[$index] = $color;
}
}
+
+ private function cacheBrailleChars(): void
+ {
+ [$from, $to] = BrailleSet::RANGE;
+
+ for ($i = $from; $i <= $to; $i++) {
+ $this->brailleCharCache[$i] = IntlChar::chr($i); | hm, is there any point in doing this and lazily loading the char on line 54? i think we could remove this function no? |
babyagi-ui | github_2023 | typescript | 80 | miurla | miurla | @@ -5,22 +5,22 @@ export class AgentExecuter {
objective: string;
modelName: string;
messageCallback: (message: Message) => void;
- statusCallback: (status: AgentStatus) => void;
+ statusCallback: (status: AgentStatus, taskId?: number | string | undefined | null) => void;
cancelCallback: () => void;
verbose: boolean = false;
- //
+
taskIdCounter: number = 0;
taskList: AgentTask[] = [];
- isRunning: boolean = false;
- //
+ isRunning!: boolean | string; | Do we need a string type? |
babyagi-ui | github_2023 | typescript | 80 | miurla | miurla | @@ -61,9 +61,56 @@ export class AgentExecuter {
this.isRunning = false;
}
- // prepare() is called before loop()
async prepare() {
this.printer.printObjective(this.objective);
}
- async loop() {}
+
+ async loop() {
+ while (this.isRunning && this.taskList.length > 0) { | I wasn't sure if I should write the loop process, but I didn't dare because the loop condition changes for each agent executor.
https://github.com/miurla/babyagi-ui/blob/main/src/agents/babycatagi/agent.ts#L528 |
babyagi-ui | github_2023 | typescript | 80 | miurla | miurla | @@ -61,9 +61,56 @@ export class AgentExecuter {
this.isRunning = false;
}
- // prepare() is called before loop()
async prepare() {
this.printer.printObjective(this.objective);
}
- async loop() {}
+
+ async loop() {
+ while (this.isRunning && this.taskList.length > 0) {
+ const currentTask = this.taskList.shift();
+ if (currentTask) {
+ await this.executeTask(currentTask);
+ }
+ }
+
+ }
+
+ async executeTask(task: AgentTask) {
+ this.statusCallback({ type: 'task-started', taskId: task?.id });
+
+ switch (task.task) {
+ case 'type1':
+ break;
+ case 'type2':
+ break;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+
+ this.statusCallback({ type: 'task-completed', taskId: task?.id });
+ }
+
+ addTask(task: AgentTask) { | I’d like to put all the task convenience functions in utils/task.ts
https://github.com/miurla/babyagi-ui/blob/main/src/utils/task.ts |
babyagi-ui | github_2023 | typescript | 80 | miurla | miurla | @@ -54,6 +54,9 @@ export type AgentStatusType =
| 'executing'
| 'prioritizing'
| 'saving'
+ | 'running' | `AgentStatusType` is mainly used to display status on the UI. I don't see how `running` is consistent with other statuses, since it is not exclusive of other statuses. |
babyagi-ui | github_2023 | others | 74 | miurla | miurla | @@ -364,7 +364,9 @@ class Translator {
'en',
'ko',
'pt',
+ 'pt-BR', | Since `pt-BR` and `ar-SA` are locale that did not exist originally, there are no directories for them and I am getting an error.
```
> babyagi-ui@0.1.0 translate
> node ./translator.cjs
[ATi18n]:> Would you like me to translate the entire project automatically to all the locales you have enabled? (y/n) n
[ATi18n]:> Would you like to synchronize translations? (y/n) y
[ATi18n]:> Enter the source language code: en
node:fs:1451
handleErrorFromBinding(ctx);
^
Error: ENOENT: no such file or directory, scandir '/Users/yoshiki/Works/next/babyagi-ui/public/locales/pt-BR'
at Object.readdirSync (node:fs:1451:3)
at Translator.getTranslationsFromDir (/Users/yoshiki/Works/next/babyagi-ui/translator.cjs:623:22)
at Translator.synchronizeTranslations (/Users/yoshiki/Works/next/babyagi-ui/translator.cjs:577:39)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async /Users/yoshiki/Works/next/babyagi-ui/translator.cjs:763:17 {
errno: -2,
syscall: 'scandir',
code: 'ENOENT',
path: '/Users/yoshiki/Works/next/babyagi-ui/public/locales/pt-BR'
}
Node.js v18.12.1
``` |
babyagi-ui | github_2023 | typescript | 57 | miurla | miurla | @@ -34,9 +35,31 @@ export const availableLanguages: Language[] = [
{ code: 'fi', name: 'Suomi', flag: '🇫🇮' },
{ code: 'no', name: 'Norsk', flag: '🇳🇴' },
{ code: 'tr', name: 'TÜRKİSH', flag: '🇹🇷' },
- { code: "pl", name: "Polski", flag: "🇵🇱" },
+ { code: 'pl', name: 'Polski', flag: '🇵🇱' },
{ code: 'zhtw', name: '中文(台灣)', flag: '🇹🇼' },
{ code: 'bg', name: 'бълежи', flag: '🇧🇬' },
+ { code: 'nl', name: 'Nederlands', flag: '🇳🇱' },
+ { code: 'sk', name: 'Slovenčina', flag: '🇸🇰' },
+ { code: 'ro', name: 'Română', flag: '🇷🇴' },
+ { code: 'lv', name: 'Latviešu', flag: '🇱🇻' },
+ { code: 'et', name: 'Eesti', flag: '🇪🇪' },
+ { code: 'hr', name: 'Hrvatski', flag: '🇭🇷' },
+ { code: 'sl', name: 'Slovenščina', flag: '🇸🇮' },
+ { code: 'el', name: 'Ελληνικά', flag: '🇬🇷' },
+ { code: 'ru', name: 'Русский', flag: '🇷🇺' },
+ { code: 'uk', name: 'Українська', flag: '🇺🇦' },
+ { code: 'sr', name: 'Српски', flag: '🇷🇸' },
+ { code: 'he', name: 'עברית', flag: '🇮🇱' },
+ { code: 'ar', name: 'العربية', flag: '🇸🇦' },
+ { code: 'fa', name: 'فارسی', flag: '🇮🇷' },
+ { code: 'ur', name: 'اردو', flag: '🇵🇰' },
+ { code: 'hi', name: 'हिन्दी', flag: '🇮🇳' }, | duplication `hi`
https://github.com/miurla/babyagi-ui/pull/57/files#diff-6703b91dc8242fb5425dfa1a282a7ea5c9a9bc92cd8f453a61aa06dc6b2eb5b0R16 |
babyagi-ui | github_2023 | typescript | 57 | miurla | miurla | @@ -34,9 +35,31 @@ export const availableLanguages: Language[] = [
{ code: 'fi', name: 'Suomi', flag: '🇫🇮' },
{ code: 'no', name: 'Norsk', flag: '🇳🇴' },
{ code: 'tr', name: 'TÜRKİSH', flag: '🇹🇷' },
- { code: "pl", name: "Polski", flag: "🇵🇱" },
+ { code: 'pl', name: 'Polski', flag: '🇵🇱' },
{ code: 'zhtw', name: '中文(台灣)', flag: '🇹🇼' },
{ code: 'bg', name: 'бълежи', flag: '🇧🇬' },
+ { code: 'nl', name: 'Nederlands', flag: '🇳🇱' },
+ { code: 'sk', name: 'Slovenčina', flag: '🇸🇰' },
+ { code: 'ro', name: 'Română', flag: '🇷🇴' },
+ { code: 'lv', name: 'Latviešu', flag: '🇱🇻' },
+ { code: 'et', name: 'Eesti', flag: '🇪🇪' },
+ { code: 'hr', name: 'Hrvatski', flag: '🇭🇷' },
+ { code: 'sl', name: 'Slovenščina', flag: '🇸🇮' },
+ { code: 'el', name: 'Ελληνικά', flag: '🇬🇷' },
+ { code: 'ru', name: 'Русский', flag: '🇷🇺' },
+ { code: 'uk', name: 'Українська', flag: '🇺🇦' }, | duplication `uk`
https://github.com/miurla/babyagi-ui/pull/57/files#diff-6703b91dc8242fb5425dfa1a282a7ea5c9a9bc92cd8f453a61aa06dc6b2eb5b0R25 |
babyagi-ui | github_2023 | others | 56 | miurla | miurla | @@ -20,7 +20,7 @@ This is a port of [babyagi](https://github.com/yoheinakajima/babyagi) with [Lang
- [x] Exporting Execution Results
- [x] Execution history
- [x] Faster speeds and fewer errors. ([😺 BabyCatAGI](https://twitter.com/yoheinakajima/status/1657448504112091136))
-- [x] i18n support ( '🇧🇷', '🇩🇪', '🇺🇸', '🇪🇸', '🇫🇷', '🇮🇳', '🇭🇺', '🇯🇵', '🇷🇺', '🇹🇭',)
+- [x] i18n support ( 🇧🇷, 🇩🇪, 🇺🇸, 🇪🇸, 🇫🇷, 🇮🇳, 🇭🇺, 🇯🇵, 🇷🇺, 🇹🇭, ... and much more) | Thx 🙏 |
babyagi-ui | github_2023 | typescript | 55 | miurla | miurla | @@ -17,6 +17,27 @@ export const availableLanguages: Language[] = [
{ code: 'ja', name: '日本語', flag: '🇯🇵' },
{ code: 'ru', name: 'Русский', flag: '🇷🇺' },
{ code: 'th', name: 'ไทย', flag: '🇹🇭' },
+ { code: 'en', name: 'English', flag: '🇺🇸' }, | In this project, availableLanguages is used directly for the selection items.
https://github.com/miurla/babyagi-ui/blob/main/src/components/Sidebar/SidebarSettings.tsx#L175
So I’d like to sort this list in ascending order by language code.
Alternatively, the sorting logic can be added on the component side. |
babyagi-ui | github_2023 | typescript | 55 | miurla | miurla | @@ -17,6 +17,27 @@ export const availableLanguages: Language[] = [
{ code: 'ja', name: '日本語', flag: '🇯🇵' },
{ code: 'ru', name: 'Русский', flag: '🇷🇺' },
{ code: 'th', name: 'ไทย', flag: '🇹🇭' },
+ { code: 'en', name: 'English', flag: '🇺🇸' },
+ { code: 'ko', name: '한국어', flag: '🇰🇷' },
+ { code: 'pt', name: 'Português', flag: '🇵🇹' },
+ { code: 'ar', name: 'العربية', flag: '🇸🇦' }, | In order to support Arabic, I think we need to support right-justification as well as text.
https://en.wikipedia.org/wiki/Right-to-left_script
So, it would be better to remove it once. |
babyagi-ui | github_2023 | others | 47 | miurla | miurla | @@ -344,16 +369,14 @@ const rl = readline.createInterface({
output: process.stdout,
});
-rl.question(`Choose a mode:\n1. Automatic mode\n2. Manual mode\n`, (answer) => {
- rl.question('Enter source language code: ', (srcLang) => {
- srcLang === '' ? (srcLang = 'en') : (srcLang = srcLang);
- rl.question('Enter target language code: ', (targetLang) => {
- targetLang === ''
- ? (targetLang = process.env.DEFAULT_TARGET_LANGUAGE || 'hu')
- : (targetLang = targetLang);
- const translator = new Translator(srcLang, targetLang);
- translator.run('src');
- rl.close();
- });
+rl.question('Enter source language code: ', (srcLang) => {
+ srcLang === '' ? (srcLang = 'en') : (srcLang = srcLang);
+ rl.question('Enter target language code: ', (targetLang) => {
+ targetLang === ''
+ ? (targetLang = process.env.DEFAULT_TARGET_LANGUAGE || 'hu') | [nits] Unnecessary |
babyagi-ui | github_2023 | others | 38 | miurla | miurla | @@ -21,7 +21,7 @@ This is a port of [babyagi](https://github.com/yoheinakajima/babyagi) with [Lang
- [x] Execution history
- [x] Faster speeds and fewer errors. ([😺 BabyCatAGI](https://twitter.com/yoheinakajima/status/1657448504112091136))
- [ ] Display the current task and task list
-- [ ] i18n support
+- [x] i18n support | 🙌 🙌 |
babyagi-ui | github_2023 | typescript | 38 | miurla | miurla | @@ -0,0 +1,112 @@
+import { SelectItem } from '@/types'; | FYI: The language selection menu was implemented separately, so this file was removed in #40. 🙏 |
babyagi-ui | github_2023 | others | 38 | miurla | miurla | @@ -6,7 +6,8 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
- "lint": "next lint"
+ "lint": "next lint",
+ "translate": "node ./translate.cjs" | File name is wrong.
`translate.cjs` -> `translator.cjs` |
babyagi-ui | github_2023 | others | 38 | miurla | miurla | @@ -0,0 +1,359 @@
+require('dotenv').config();
+const fs = require('fs');
+const path = require('path');
+const { Configuration, OpenAIApi } = require('openai');
+
+class Translator { | 🆒 |
basaran | github_2023 | others | 150 | hyperonym | fardeon | @@ -0,0 +1,46 @@
+name: basaran
+adopt-info: basaran
+summary: Basaran is an open-source alternative to the OpenAI text completion API.
+description: |
+ Basaran is an open-source alternative to the OpenAI text completion API.
+ It provides a compatible streaming API for your Hugging Face Transformers-based text generation models.
+
+issues: https://github.com/hyperonym/basaran/issues
+source-code: https://github.com/hyperonym/basaran
+license: MIT
+
+base: core22
+grade: stable
+confinement: strict
+
+apps:
+
+ basaran:
+ command: bin/python3 -m basaran
+ command-chain: [bin/launcher]
+ plugs: [home, network, network-bind, removable-media]
+
+ download: | I'm not familiar with snap, would this make the user install a `download` command? If so, it might be too broad. Perhaps something like `basaran-download` or `download-model` would be less ambiguous? |
basaran | github_2023 | others | 34 | hyperonym | peakji | @@ -40,13 +40,19 @@ body {
.pg-prompt {
-moz-user-modify: read-write-plaintext-only;
-webkit-user-modify: read-write-plaintext-only; | Remove `-moz-user-modify` and `-webkit-user-modify` since we're now using textarea? |
basaran | github_2023 | javascript | 34 | hyperonym | peakji | @@ -434,8 +434,14 @@ class Inspector {
}
});
+ let resizePrompt = () => {
+ prompt.style.height = 0;
+ prompt.style.height = prompt.scrollHeight + "px"; | Great solution! Actually the only reason I use `contenteditable` is just to make it auto-growing. 😂 |
basaran | github_2023 | others | 34 | hyperonym | peakji | @@ -16,10 +16,11 @@ <h4 class="pg-title">{{ model }}</h4>
<div class="pg-body">
<div class="pg-left">
<div class="pg-inputs">
- <div class="pg-prompt" role="textbox" placeholder="Enter prompt here" contenteditable></div>
+ <textarea class="pg-prompt" placeholder="Enter prompt here"></textarea>
</div>
<div class="pg-actions">
<button class="pg-button pg-submit">Submit</button>
+ <button class="pg-button pg-stop">Stop</button> | The only problem with adding another button is that it may cause wrapping on narrower screens. Perhaps we could display an ellipsis for the last two buttons?

|
basaran | github_2023 | others | 34 | hyperonym | peakji | @@ -0,0 +1,122 @@
+[
+ {
+ "id": "default",
+ "name": "Default",
+ "temperature": 0.7,
+ "top_k": 40,
+ "top_p": 1,
+ "typical_p": 1,
+ "penalty_alpha": 0,
+ "repetition_penalty": 1.17 | The default preset should be consistent with the OpenAI API, so I think it should be 0 here?
Reference: https://platform.openai.com/docs/api-reference/completions/create |
basaran | github_2023 | others | 34 | hyperonym | peakji | @@ -38,15 +38,19 @@ body {
}
.pg-prompt {
- -moz-user-modify: read-write-plaintext-only;
- -webkit-user-modify: read-write-plaintext-only;
+ background-color: transparent;
+ border: 0;
+ box-sizing: border-box;
font-size: 16px;
+ font-family: inherit;
line-height: 24px;
min-height: 72px;
outline: 0 solid transparent;
overflow-wrap: anywhere;
padding: 16px;
+ resize: vertical; | Can we use `resize: none;` instead to hide the little resize handle and let auto-growing do the job? |
openai-go | github_2023 | go | 5 | rakyll | rakyll | @@ -29,3 +35,27 @@ type Image struct {
URL string `json:"url,omitempty"`
Base64JSON string `json:"b64_json,omitempty"`
}
+
+func (c *Image) Save(filename string, toBase64 bool) (ok bool, err error) { | Base64JSON is populated by the server when response type is set to `b64_json`. We shouldn't mutate it.
On the other hand, instead of assuming that the user have access to a file system, we should turn this method into something that returns an io.ReadCloser for flexibility. What about something like below?
```
func (i *Image) Reader() (io.ReadCloser, error) {
if i.URL != "" {
resp, err := http.Get(i.URL)
if err != nil {
return nil, err
}
return resp.Body, nil
}
if i.Base64JSON != "" {
decoded, err := base64.RawStdEncoding.DecodeString(i.Base64JSON)
if err != nil {
return nil, err
}
return ioutil.NopCloser(bytes.NewBuffer(decoded)), nil
}
return nil, errors.New("no image data")
}
``` |
openai-go | github_2023 | go | 2 | rakyll | rakyll | @@ -78,6 +79,71 @@ func (s *Session) MakeRequest(ctx context.Context, endpoint string, input, outpu
return json.NewDecoder(resp.Body).Decode(output)
}
+// Upload makes a multi-part form data upload them with
+// session's API key. Upload combines the file with the given params
+// and unmarshals the response as output.
+func (s *Session) Upload(ctx context.Context, endpoint string, file io.Reader, fileExt string, params url.Values, output interface{}) error {
+ pr, pw := io.Pipe()
+ mw := multipart.NewWriter(pw)
+ go func() {
+ err := upload(mw, file, fileExt, params)
+ pw.CloseWithError(err)
+ }()
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, pr)
+ if err != nil {
+ return err
+ }
+ if s.apiKey != "" {
+ req.Header.Set("Authorization", "Bearer "+s.apiKey)
+ }
+ if s.OrganizationID != "" {
+ req.Header.Set("OpenAI-Organization", s.OrganizationID)
+ }
+ req.Header.Set("Content-Type", mw.FormDataContentType())
+ resp, err := s.HTTPClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("error sending request: %w", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode < 200 || resp.StatusCode >= 400 { | We should probably consider splitting this into its own function. |
OpenNept4une | github_2023 | others | 234 | OpenNeptune3D | barrenechea | @@ -287,6 +306,20 @@ install_feature() {
# Proceed if the user agrees or if auto_yes is true
if [[ $user_input =~ ^[Yy]$ || -z $user_input || $auto_yes = "true" ]]; then
echo -e "Running $feature_name Installer...\n"
+
+ if [ "$feature_name" = "Updated Display Firmware" ]; then
+ if [ -d "${HOME}/display_firmware" ]; then
+ echo "Display_Firmware installed. Proceeding with installer!"
+ else
+ echo "Display_Firmware not installed. Downloading"
+ mkdir display_firmware
+ git clone --filter=blob:none --sparse https://github.com/OpenNeptune3D/display_firmware.git "${HOME}/display_firmware" | What `--filter=blob:none --sparse` brings to the table? Just curious |
OpenNept4une | github_2023 | others | 234 | OpenNeptune3D | barrenechea | @@ -763,7 +800,7 @@ print_menu() {
echo ""
echo -e "(${R} Q ${NC}) Quit"
echo "=========================================================="
- echo "Select an option by entering (1-7 / q):"
+ echo "Select an option by entering (1-6 / q):" | I think the main menu still has 7 options? It seems the added option for `display_firmware` is in the Advanced menu, and wouldn't require to decrease the options from the main menu. Can you double-check please?
```suggestion
echo "Select an option by entering (1-7 / q):"
``` |
OpenNept4une | github_2023 | others | 153 | OpenNeptune3D | anarsoul | @@ -59,19 +59,18 @@ gcode:
Part_Light_ON
G92 E0
G90 ; Use absolute coordinates
- BED_MESH_CLEAR
- G28 | It may be better to home, then move head up by 50mm, and then start to heat the bed. Otherwise we don't know where the head is, and it may be heating up from the bed if it is too low |
OpenNept4une | github_2023 | others | 105 | OpenNeptune3D | barrenechea | @@ -24,7 +24,7 @@ variable_detach_macro: 'Dock_Probe' # The macro that is used to store th
# The following variables are for adjusting adaptive purge settings for KAMP.
variable_purge_height: 0.8 # Z position of nozzle during purge, default is 0.8.
variable_tip_distance: 1.8 # Distance between tip of filament and nozzle before purge. Should be similar to PRINT_END final retract amount.
-variable_purge_margin: 10 # Distance the purge will be in front of the print area, default is 10.
+variable_purge_margin: 15 # Distance the purge will be in front of the print area, default is 10. | Awesome tweak! |
OpenNept4une | github_2023 | others | 88 | OpenNeptune3D | barrenechea | @@ -1,19 +1,18 @@
<p align="center">
- <img src="pictures/OpenNept4une.png" alt="OpenNept4une Logo">
+ <img src="pictures/OpenNept4une.png" width="350" alt="OpenNept4une Logo">
<h1 align="center">OpenNept4une</h1>
+ <h1 align="center">De-Elegoo-izing the Neptune 4 Series 3D Printers</h1>
</p>
-## De-Elegoo-izing the Neptune 4 Series 3D Printers
-
-**NOTE:** The Touch-Screen Display Service is in Beta (Most functions work and it receives frequent code updates). An alternative until the service is completed is the mobileraker phone app
-
-**LED’s, ADXL & WiFi Working on all Variants**
-
### Credits:
-- Community Members: SQUIRRELYMOOSE, DanDonut, Jaerax, SmartHome42/Printernbeer, Tom's Basement & Phillip Thelen
-- Projects:
+#### Community Members:
+
+ *Phillip Thelen, barrenechea, SQUIRRELYMOOSE, DanDonut & Jaerax* | I just noticed this, thank you!! |
OpenNept4une | github_2023 | others | 71 | OpenNeptune3D | barrenechea | @@ -0,0 +1,128 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our
+community a harassment-free experience for everyone, regardless of age, body
+size, visible or invisible disability, ethnicity, sex characteristics, gender
+identity and expression, level of experience, education, socio-economic status,
+nationality, personal appearance, race, religion, or sexual identity
+and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming,
+diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our
+community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes,
+ and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the
+ overall community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or
+ advances of any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email
+ address, without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of
+acceptable behavior and will take appropriate and fair corrective action in
+response to any behavior that they deem inappropriate, threatening, offensive,
+or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are
+not aligned to this Code of Conduct, and will communicate reasons for moderation
+decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when
+an individual is officially representing the community in public spaces.
+Examples of representing our community include using an official e-mail address,
+posting via an official social media account, or acting as an appointed
+representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported to the community leaders responsible for enforcement at
+[@phillipthelen](https://github.com/phillipthelen). | GitHub does not allow direct messaging to users. Maybe consider setting up a point of contact for this project? So you don't have to disclose PII.
Or maybe refer to Elegoo Discord with your username 😄 |
snagboot | github_2023 | others | 53 | bootlin | rgantois | @@ -0,0 +1,46 @@
+ | You should link to this new doc file from an existing one, or people won't find it. Linking this one from docs/snagflash.md seems appropriate to me. |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -0,0 +1,166 @@
+# Copyright 2025 Collabora Ltd.
+#
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Author: Arnaud Patard <arnaud.patard@collabora.com>
+
+from snagrecover.utils import BinFileHeader
+from dataclasses import dataclass
+import struct
+
+SPARSE_FILEHEADER_LEN = 28
+SPARSE_CHUNKHEADER_LEN = 12
+SPARSE_FILE_MAJOR = 1
+SPARSE_FILE_MINOR = 0
+MAGIC = 0xED26FF3A
+DEFAULT_BLOCK_SIZE = 4096
+CHUNK_TYPE_RAW = 0xcac1
+CHUNK_TYPE_FILL = 0xcac2
+CHUNK_TYPE_DONTCARE = 0xcac3
+CHUNK_TYPE_CRC32 = 0xcac4
+
+class SparseFileFormatError(Exception):
+ pass | I guess this is WIP. When implementing this, you can use logger.error() + sys.exit(-1) |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -0,0 +1,69 @@
+# Copyright 2025 Collabora Ltd.
+#
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Author: Arnaud Patard <arnaud.patard@collabora.com>
+
+
+from snagflash.android_sparse_file.sparse import AndroidSparseFile
+from snagflash.android_sparse_file.sparse import SPARSE_CHUNKHEADER_LEN
+from snagflash.android_sparse_file.sparse import CHUNK_TYPE_DONTCARE | Please group these into a single import line |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -30,6 +35,9 @@
for more information on fastboot support in U-Boot.
"""
+class FastbootError(Exception):
+ pass | same comment as for SparseFileFormatError. Also, could you change other Fastboot methods in this file to use this as well? |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -218,3 +226,43 @@ def reset(self):
self.dev.write(self.ep_out, packet, timeout=self.timeout)
+ def flash_sparse(self, args: str):
+ """
+ Download and flash an android sparse file.
+ If the file is too big, it's splitting into
+ smaller android sparse files.
+ """
+ try:
+ maxsize = int(self.getvar("max-download-size"), 0)
+ except Exception as e:
+ raise FastbootError("Failed to get fastboot max-download-size variable") from e
+ if maxsize == 0:
+ raise FastbootError("Fastboot variable max-download-size is 0")
+ arg_list = args.split(':')
+ cnt = len(arg_list)
+ if cnt != 2:
+ raise FastbootError(f"Wrong arguments count {cnt}, expected 2. Given {args}")
+ fname = arg_list[0]
+ if not os.path.exists(fname):
+ raise FastbootError(f"File {fname} does not exist")
+ part = arg_list[1]
+ with tempfile.TemporaryDirectory() as tmp: | Could you make sure that this context manager automatically remove the directory when you're done with it? |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -0,0 +1,67 @@
+# Copyright 2025 Collabora Ltd.
+#
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Author: Arnaud Patard <arnaud.patard@collabora.com>
+
+
+from snagflash.android_sparse_file.sparse import AndroidSparseFile, SPARSE_CHUNKHEADER_LEN, CHUNK_TYPE_DONTCARE
+
+def unpack(path, outpath):
+ with open(outpath, "wb+") as raw_file:
+ sparse_file = AndroidSparseFile(True, True)
+ sparse_file.open(path)
+
+ flen = 0
+ while True:
+ (header, data) = sparse_file.read_chunk()
+ if header is None:
+ break
+ if data is not None:
+ raw_file.write(data)
+ flen += header.get_raw_size()
+ assert flen == sparse_file.file_header.get_raw_size()
+
+
+def split(path, pattern, bufsize):
+ flist = []
+ sparse_file = AndroidSparseFile(True, False)
+ sparse_file.open(path) | it doesn't seem like this is closed anywhere |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -226,3 +230,41 @@ def reset(self):
self.dev.write(self.ep_out, packet, timeout=self.timeout)
+ def flash_sparse(self, args: str):
+ """
+ Download and flash an android sparse file.
+ If the file is too big, it's splitting into
+ smaller android sparse files.
+ """
+ try:
+ maxsize = int(self.getvar("max-download-size"), 0)
+ except Exception as e:
+ raise FastbootError("Failed to get fastboot max-download-size variable") from e
+ if maxsize == 0:
+ raise FastbootError("Fastboot variable max-download-size is 0")
+ arg_list = args.split(':')
+ cnt = len(arg_list)
+ if cnt != 2:
+ raise FastbootError(f"Wrong arguments count {cnt}, expected 2. Given {args}")
+ fname = arg_list[0]
+ if not os.path.exists(fname):
+ raise FastbootError(f"File {fname} does not exist")
+ part = arg_list[1]
+ with tempfile.TemporaryDirectory() as tmp:
+ temppath = os.path.join(tmp, '{count}.img')
+ try:
+ splitfiles = split(fname, temppath, maxsize)
+ logger.info(f"Splitted fastboot file into {len(splitfiles)} file(s)")
+ for f in splitfiles:
+ logger.info(f"Uploading {f}") | That would be "Downloading" not "Uploading", as per the Fastboot spec |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -226,3 +230,41 @@ def reset(self):
self.dev.write(self.ep_out, packet, timeout=self.timeout)
+ def flash_sparse(self, args: str):
+ """
+ Download and flash an android sparse file.
+ If the file is too big, it's splitting into
+ smaller android sparse files.
+ """
+ try:
+ maxsize = int(self.getvar("max-download-size"), 0)
+ except Exception as e:
+ raise FastbootError("Failed to get fastboot max-download-size variable") from e
+ if maxsize == 0:
+ raise FastbootError("Fastboot variable max-download-size is 0")
+ arg_list = args.split(':')
+ cnt = len(arg_list)
+ if cnt != 2:
+ raise FastbootError(f"Wrong arguments count {cnt}, expected 2. Given {args}")
+ fname = arg_list[0]
+ if not os.path.exists(fname):
+ raise FastbootError(f"File {fname} does not exist")
+ part = arg_list[1]
+ with tempfile.TemporaryDirectory() as tmp:
+ temppath = os.path.join(tmp, '{count}.img')
+ try:
+ splitfiles = split(fname, temppath, maxsize)
+ logger.info(f"Splitted fastboot file into {len(splitfiles)} file(s)")
+ for f in splitfiles:
+ logger.info(f"Uploading {f}")
+ try:
+ self.download(f)
+ except Exception as e:
+ raise FastbootError(f"Failed to upload: {e}") from e | ditto |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -226,3 +230,41 @@ def reset(self):
self.dev.write(self.ep_out, packet, timeout=self.timeout)
+ def flash_sparse(self, args: str):
+ """
+ Download and flash an android sparse file.
+ If the file is too big, it's splitting into
+ smaller android sparse files.
+ """
+ try:
+ maxsize = int(self.getvar("max-download-size"), 0)
+ except Exception as e:
+ raise FastbootError("Failed to get fastboot max-download-size variable") from e
+ if maxsize == 0:
+ raise FastbootError("Fastboot variable max-download-size is 0")
+ arg_list = args.split(':')
+ cnt = len(arg_list)
+ if cnt != 2:
+ raise FastbootError(f"Wrong arguments count {cnt}, expected 2. Given {args}")
+ fname = arg_list[0]
+ if not os.path.exists(fname):
+ raise FastbootError(f"File {fname} does not exist")
+ part = arg_list[1]
+ with tempfile.TemporaryDirectory() as tmp:
+ temppath = os.path.join(tmp, '{count}.img') | Is the second parameter supposed to be an f-string? Also, I don't see "count" defined anywhere. |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -226,3 +230,41 @@ def reset(self):
self.dev.write(self.ep_out, packet, timeout=self.timeout)
+ def flash_sparse(self, args: str):
+ """
+ Download and flash an android sparse file.
+ If the file is too big, it's splitting into
+ smaller android sparse files.
+ """
+ try:
+ maxsize = int(self.getvar("max-download-size"), 0)
+ except Exception as e:
+ raise FastbootError("Failed to get fastboot max-download-size variable") from e
+ if maxsize == 0:
+ raise FastbootError("Fastboot variable max-download-size is 0")
+ arg_list = args.split(':')
+ cnt = len(arg_list)
+ if cnt != 2:
+ raise FastbootError(f"Wrong arguments count {cnt}, expected 2. Given {args}")
+ fname = arg_list[0]
+ if not os.path.exists(fname):
+ raise FastbootError(f"File {fname} does not exist")
+ part = arg_list[1]
+ with tempfile.TemporaryDirectory() as tmp:
+ temppath = os.path.join(tmp, '{count}.img')
+ try:
+ splitfiles = split(fname, temppath, maxsize)
+ logger.info(f"Splitted fastboot file into {len(splitfiles)} file(s)") | nit: s/Splitted/Split/ |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -0,0 +1,67 @@
+# Copyright 2025 Collabora Ltd.
+#
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Author: Arnaud Patard <arnaud.patard@collabora.com>
+
+
+from snagflash.android_sparse_file.sparse import AndroidSparseFile, SPARSE_CHUNKHEADER_LEN, CHUNK_TYPE_DONTCARE
+
+def unpack(path, outpath): | Is this function used anywhere? If not, please remove it. |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -0,0 +1,171 @@
+# Copyright 2025 Collabora Ltd.
+#
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Author: Arnaud Patard <arnaud.patard@collabora.com>
+
+from snagrecover.utils import BinFileHeader
+from dataclasses import dataclass
+import struct
+
+SPARSE_FILEHEADER_LEN = 28
+SPARSE_CHUNKHEADER_LEN = 12
+SPARSE_FILE_MAJOR = 1
+SPARSE_FILE_MINOR = 0
+MAGIC = 0xED26FF3A
+DEFAULT_BLOCK_SIZE = 4096
+CHUNK_TYPE_RAW = 0xcac1
+CHUNK_TYPE_FILL = 0xcac2
+CHUNK_TYPE_DONTCARE = 0xcac3
+CHUNK_TYPE_CRC32 = 0xcac4
+
+class SparseFileFormatError(Exception):
+ def __init__(self, message):
+ self.message = message
+ super().__init__(self.message)
+
+ def __str__(self):
+ return f"Sparse file format error: {self.message}"
+
+@dataclass
+class AndroidSparseHeader(BinFileHeader):
+ magic: int = MAGIC
+ major: int = 1
+ minor: int = 0
+ header_len: int = SPARSE_FILEHEADER_LEN
+ chunk_header_len: int = SPARSE_CHUNKHEADER_LEN
+ block_size: int = DEFAULT_BLOCK_SIZE
+ blocks: int = 0
+ chunks: int = 0
+ csum: int = 0
+
+ fmt = "<IHHHHIIII"
+ class_size = SPARSE_FILEHEADER_LEN
+
+ # Size of the raw file
+ def get_raw_size(self):
+ return self.blocks * self.block_size
+
+
+ def check(self):
+ if self.magic != MAGIC:
+ raise SparseFileFormatError(f"Invalid magic {self.magic}")
+ if self.major != SPARSE_FILE_MAJOR or self.minor != SPARSE_FILE_MINOR:
+ raise SparseFileFormatError(f"Invalid major or minor {self.major}.{self.minor}")
+ if self.header_len != SPARSE_FILEHEADER_LEN:
+ raise SparseFileFormatError(f"Invalid header length specified in header {self.header_len}")
+ if self.chunk_header_len != SPARSE_CHUNKHEADER_LEN:
+ raise SparseFileFormatError(f"Invalid chunk header length specified in header {self.chunk_header_len}")
+ if self.block_size % 4:
+ raise SparseFileFormatError(f"Invalid block size {self.block_size}. Should be multiple of 4")
+
+@dataclass
+class AndroidChunkHeader(BinFileHeader):
+ type: int = CHUNK_TYPE_DONTCARE
+ rsvd: int = 0
+ size: int = 0
+ total_size: int = SPARSE_CHUNKHEADER_LEN
+
+ fmt = "<HHII"
+ class_size = SPARSE_CHUNKHEADER_LEN
+
+ def get_data_size(self, block_size):
+ if self.type == CHUNK_TYPE_DONTCARE:
+ return 0
+ elif self.type == CHUNK_TYPE_RAW:
+ return self.size * block_size
+ elif self.type == CHUNK_TYPE_FILL:
+ return 4
+ elif self.type == CHUNK_TYPE_CRC32:
+ return 4
+
+ def check(self):
+ if self.type not in [CHUNK_TYPE_RAW, CHUNK_TYPE_FILL, CHUNK_TYPE_DONTCARE, CHUNK_TYPE_CRC32]:
+ raise SparseFileFormatError(f"Invalid chunk type {self.type}")
+
+class AndroidSparseFile():
+ def __init__(self, read, unpack): | It seems like the "unpack" argument is always initialized to False, except in the unpack() function which isn't called anywhere. So I suppose this second parameter could be dropped along with all associated conditional paths. |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -0,0 +1,67 @@
+# Copyright 2025 Collabora Ltd.
+#
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Author: Arnaud Patard <arnaud.patard@collabora.com>
+
+
+from snagflash.android_sparse_file.sparse import AndroidSparseFile, SPARSE_CHUNKHEADER_LEN, CHUNK_TYPE_DONTCARE
+
+def unpack(path, outpath):
+ with open(outpath, "wb+") as raw_file:
+ sparse_file = AndroidSparseFile(True, True)
+ sparse_file.open(path)
+
+ flen = 0
+ while True:
+ (header, data) = sparse_file.read_chunk()
+ if header is None:
+ break
+ if data is not None:
+ raw_file.write(data)
+ flen += header.get_raw_size()
+ assert flen == sparse_file.file_header.get_raw_size()
+
+
+def split(path, pattern, bufsize):
+ flist = []
+ sparse_file = AndroidSparseFile(True, False)
+ sparse_file.open(path)
+ split_count = 0
+
+ outf = AndroidSparseFile(False, False)
+ fname = pattern.format(count=split_count) | I'd rather you used "new_fname" here, to distinguish it from the "fname" used in flash_sparse(), which refers to the input sparse file. |
snagboot | github_2023 | python | 53 | bootlin | rgantois | @@ -0,0 +1,67 @@
+# Copyright 2025 Collabora Ltd.
+#
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Author: Arnaud Patard <arnaud.patard@collabora.com>
+
+
+from snagflash.android_sparse_file.sparse import AndroidSparseFile, SPARSE_CHUNKHEADER_LEN, CHUNK_TYPE_DONTCARE
+
+def unpack(path, outpath):
+ with open(outpath, "wb+") as raw_file:
+ sparse_file = AndroidSparseFile(True, True)
+ sparse_file.open(path)
+
+ flen = 0
+ while True:
+ (header, data) = sparse_file.read_chunk()
+ if header is None:
+ break
+ if data is not None:
+ raw_file.write(data)
+ flen += header.get_raw_size()
+ assert flen == sparse_file.file_header.get_raw_size()
+
+
+def split(path, pattern, bufsize):
+ flist = []
+ sparse_file = AndroidSparseFile(True, False)
+ sparse_file.open(path)
+ split_count = 0
+
+ outf = AndroidSparseFile(False, False)
+ fname = pattern.format(count=split_count)
+ outf.open(fname, sparse_file.file_header.block_size)
+ flist.append(fname)
+
+ while True:
+ (header, data) = sparse_file.read_chunk()
+ if header is None:
+ outf.close()
+ break
+ rem_space = bufsize - outf.size
+ if header.total_size > rem_space:
+ split_blocks = int(rem_space / outf.file_header.block_size)
+ split = split_blocks * outf.file_header.block_size
+ rem = header.total_size - split - SPARSE_CHUNKHEADER_LEN
+ rem_blocks = int(rem / outf.file_header.block_size)
+ # non RAW chunks. can't split them.
+ if header.total_size == (SPARSE_CHUNKHEADER_LEN + 4) or header.total_size == SPARSE_CHUNKHEADER_LEN: | This seems like quite a roundabout way to check for a non-raw chunk. Why not simply check "header.type != CHUNK_TYPE_RAW"? |
snagboot | github_2023 | python | 55 | bootlin | rgantois | @@ -0,0 +1,29 @@
+import usb
+import logging
+logger = logging.getLogger("snagrecover")
+from snagrecover.firmware.firmware import run_firmware
+from snagrecover.utils import get_usb
+from snagrecover.config import recovery_config
+from snagrecover.protocols import dfu | The dfu import is unused, please remove it |
snagboot | github_2023 | python | 28 | bootlin | rgantois | @@ -77,17 +77,70 @@
"imx93"
]
+# SoCs that use raw bulk endpoints rather than HID
+raw_bulk_ep_socs = [
+"imx53",
+]
+
+def build_hid_dev(vid, pid):
+ try:
+ return hid.Device(vid, pid)
+ except hid.HIDException:
+ access_error("USB HID", f"{vid:04x}:{pid:04x}")
+
+def build_raw_ep_dev(vid, pid):
+ dev = usb.core.find(idVendor=vid, idProduct=pid)
+ if dev is None:
+ access_error("USB RAW", f"{vid:04x}:{pid:04x}")
+
+ class Adapter: | Could you please move this class definition outside of the function body? |
snagboot | github_2023 | python | 28 | bootlin | rgantois | @@ -145,49 +147,157 @@ def write32(self, addr: int, value: int) -> bool:
logger.debug(f"Sending SDP packet {packet}")
self.dev.write(packet)
self.check_hab()
- complete_status = self.dev.read(65, timeout=5000)[1:5]
+ complete_status = self._read(64, timeout=5000)[:4]
self.end_cmd()
return complete_status == b"\x12\x8A\x8A\x12"
def write_dcd(self, blob: bytes, addr: int, offset: int, size: int) -> bool:
- return self.write_blob(blob, addr, offset, size, write_dcd=True)
+ if self.is_hid():
+ return self.write_blob(blob, addr, offset, size, write_dcd=True)
+
+ # Non HID devices do not have a DCD_WRITE command
+ # They do have a "FileType" byte in WRITE_FILE but that does not
+ # appear to actually process the DCD immediately (which we need to
+ # configure dram to download u-boot)
+ # So instead we manually interpret the DCD as individual read / write
+ # operations. This is what imx_usb_loader does too.
+ tag, lg, version = struct.unpack(">BHB", blob[offset:offset + 4])
+ if tag != 0xD2:
+ raise ValueError("Bad DCD tag %02x" % tag)
+ if version != 0x40:
+ raise ValueError("Bad DCD version %02x" % version)
+
+ pos = offset + 4
+ end = offset + lg
+ while pos < end:
+ tag, lg, param = struct.unpack(">BHB", blob[pos:pos + 4])
+
+ def invoke_for_each_addr_data(fn, param=param, pos=pos, lg=lg): | I find this a bit hard to read. Could you please move this function definition outside of the SDPCommand class def? I think it would be more appropriate since it doesn't explicitly use the class attributes. Plus, it would tame the indentation a bit. |
snagboot | github_2023 | python | 25 | bootlin | rgantois | @@ -32,22 +32,24 @@ def dfu_cli(args):
pid = int(dev_addr[1], 16)
dev = get_usb(vid, pid)
dev.default_timeout = int(args.timeout)
- for dfu_config in args.dfu_config:
- (altsetting,sep,path) = dfu_config.partition(":")
- altsetting = int(altsetting)
- with open(path, "rb") as file:
- blob = file.read(-1)
- size = len(blob)
- print(f"Downloading {path} to altsetting {altsetting}...")
- logger.debug(f"DFU config altsetting:{altsetting} size:0x{size:x} path:{path}")
+ altsetting = 0
+ if args.dfu_config:
+ for dfu_config in args.dfu_config: | Could you please move the body of this `for` loop into a separate function? The indentation is getting a little too deep here. |
snagboot | github_2023 | others | 24 | bootlin | rgantois | @@ -260,3 +260,33 @@ DM firmware, U-Boot SPL for A53 and device tree blobs
configuration:
* path
+## For TI AM62Ax devices
+
+[example](../src/snagrecover/templates/am62ax.yaml)
+
+**Warning** Please refer to
+[this documentation](https://software-dl.ti.com/processor-sdk-linux/esd/AM62AX/latest/exports/docs/linux/Foundational_Components/U-Boot/UG-General-Info.html#build-u-boot) | This link would be useful to have in the docs but since the rest of the doc is identical to the AM62x case, could you just rename the AM62x doc section to AM62x/AM62AX and put this link there? |
snagboot | github_2023 | python | 21 | bootlin | rgantois | @@ -34,7 +34,7 @@ def dfu_cli(args):
dev.default_timeout = int(args.timeout)
for dfu_config in args.dfu_config:
(altsetting,sep,path) = dfu_config.partition(":")
- if args.size: | This is actually a deprecated command line arg which is why you got an AttributeError. Could you please remove this check entirely? |
snagboot | github_2023 | python | 21 | bootlin | rgantois | @@ -34,7 +34,7 @@ def dfu_cli(args):
dev.default_timeout = int(args.timeout)
for dfu_config in args.dfu_config:
(altsetting,sep,path) = dfu_config.partition(":")
- if args.size:
+ if hasattr(args, "size"): | This entire if/else block and the `if size is None` check a few lines below will be unecessary. Could you please remove those? |
snagboot | github_2023 | python | 22 | bootlin | rgantois | @@ -162,7 +163,11 @@ def detach(self, partid: int):
self.set_partition(partid)
self.get_status()
logger.info("Sending DFU_DETACH...")
- self.dev.ctrl_transfer(0xa1, 0, wValue=0x7530, wIndex=0, data_or_wLength=0)
+ try:
+ self.dev.ctrl_transfer(0xa1, 0, wValue=0x7530, wIndex=0, data_or_wLength=0)
+ except usb.core.USBError as e: | Could you please add an else block with a warning log? |
pyspark-ai | github_2023 | others | 177 | pyspark-ai | gengliangwang | @@ -19,6 +19,14 @@ nav:
- udf_generation.md
- contributing.md
- resources.md
+ - Examples:
+ - "notebooks/create_udf.ipynb"
+ - "notebooks/example.ipynb" | Shall we move this one to the first so that users can have a quick overview? |
pyspark-ai | github_2023 | python | 195 | pyspark-ai | grundprinzip | @@ -582,7 +582,7 @@ def plot_df(
instruction = f"The purpose of the plot: {desc}" if desc is not None else ""
tags = self._get_tags(cache)
plot_chain = PythonExecutor(
- df=df,
+ df=DataFrameLike(df), | Interesting, was this enough for you to silence pydantic? Down the path it uses the spark sql chain and this was expecting a classic DataFrame and I had to change the annotation in the pydantic BaseModel |
pyspark-ai | github_2023 | others | 107 | pyspark-ai | gengliangwang | @@ -37,6 +37,7 @@ grpcio = ">=1.56.0"
plotly = "^5.15.0"
pyarrow = ">=4.0.0"
grpcio-status = ">=1.56.0"
+pyfakefs = "^5.2.4" | @xinrong-meng since it's just for benchmark, we can move the new one to [tool.poetry.dev-dependencies] |
pyspark-ai | github_2023 | python | 107 | pyspark-ai | gengliangwang | @@ -0,0 +1,160 @@
+import contextlib
+import io
+from pyfakefs.fake_filesystem_unittest import Patcher
+
+from pyspark.sql import SparkSession
+from pyspark_ai import SparkAI
+from pyspark_ai.ai_utils import AIUtils
+from benchmark.plot.benchmark_util import *
+
+
+def prep_df(spark_ai):
+ data = [
+ ("2023-08-30", 184.94, 187.85, 184.74, 187.65, 60590000),
+ ("2023-08-31", 187.70, 190.00, 187.50, 189.50, 58500000),
+ ("2023-09-01", 189.60, 192.00, 189.40, 191.00, 57400000),
+ ("2023-09-02", 191.10, 193.50, 190.90, 192.50, 56300000),
+ ("2023-09-03", 192.60, 195.00, 192.40, 194.00, 55200000),
+ ("2023-09-04", 194.10, 196.50, 193.90, 195.50, 54100000),
+ ("2023-09-05", 195.60, 198.00, 195.40, 197.00, 53000000),
+ ("2023-09-06", 184.94, 187.85, 184.74, 187.65, 60540000),
+ ("2023-09-07", 188.70, 191.00, 187.50, 189.50, 58800000),
+ ("2023-09-08", 189.60, 192.00, 187.40, 191.50, 57300000),
+ ("2023-09-09", 191.10, 193.50, 190.90, 192.50, 56900000),
+ ("2023-09-10", 192.60, 196.00, 192.40, 194.00, 54200000),
+ ("2023-09-11", 194.10, 196.50, 193.90, 194.50, 54800000),
+ ("2023-09-12", 195.60, 198.00, 195.40, 196.00, 53600000),
+ ]
+ df = spark_ai._spark.createDataFrame(data, ["DATE", "OPEN", "HIGH", "LOW", "CLOSE", "VOLUME"])
+ return df
+
+import logging
+from io import StringIO
+
+def capture_plot_logs(df, desc_plot, spark_ai):
+ root_logger = logging.getLogger()
+ buffer = StringIO()
+ ch = logging.StreamHandler(buffer)
+ root_logger.addHandler(ch)
+
+ with spark_ai._logger.disable_code_colorization():
+ df.ai.plot(desc_plot)
+
+ log_contents = buffer.getvalue()
+ root_logger.removeHandler(ch)
+ return log_contents
+
+
+def substitute_show_to_json(string_list):
+ import re
+ modified_list = []
+ for string in string_list:
+ modified_string = re.sub(r'(\w+)\.show\(\)', r'print(\1.to_json())', string)
+ modified_list.append(modified_string)
+ return modified_list
+
+
+def dict_diff(dict1, dict2):
+ diff = {}
+
+ # Check keys in dict1 but not in dict2
+ for key in dict1.keys():
+ if key not in dict2:
+ diff[key] = ("Only in dict1:", dict1[key])
+ elif dict1[key] != dict2[key]:
+ diff[key] = ("Different values:", dict1[key], dict2[key])
+
+ # Check keys in dict2 but not in dict1
+ for key in dict2.keys():
+ if key not in dict1:
+ diff[key] = ("Only in dict2:", dict2[key])
+
+ return diff
+
+
+def generate_golden_json(df):
+ fig_dicts = []
+ fig_dicts.append(f1(df)) | nit: not a big deal but we can assign better names to these funcitons |
pyspark-ai | github_2023 | others | 182 | pyspark-ai | gengliangwang | @@ -31,6 +31,7 @@ pygments = "^2.15.1"
# plot extras
pandas = { version = ">=1.0.5", optional = true }
plotly = { version = "^5.15.0", optional = true }
+pyarrow = { version = ">=4.0.0", optional = true } | pyarrow is used on plotting ?
As per https://spark.apache.org/docs/2.4.0/sql-pyspark-pandas-with-arrow.html, seems so.. |
pyspark-ai | github_2023 | others | 176 | pyspark-ai | gengliangwang | @@ -69,7 +69,7 @@ llm = AzureChatOpenAI(
spark_ai = SparkAI(llm=llm)
spark_ai.activate() # active partial functions for Spark DataFrame
```
-As per [Microsoft's Data Privacy page](https://learn.microsoft.com/en-us/legal/cognitive-services/openai/data-privacy), using the Azure OpenAI service can provide better data privacy and security.
+Using the Azure OpenAI service can provide better data privacy and security, as per [Microsoft's Data Privacy page](https://learn.microsoft.com/en-us/legal/cognitive-services/openai/data-privacy). | let's remove the changes from the other PR about README |
pyspark-ai | github_2023 | others | 176 | pyspark-ai | gengliangwang | @@ -127,28 +127,6 @@ Now when you call df.ai.transform as before, the agent will use word embeddings
For a detailed walkthrough, please refer to our [vector_similarity_search.ipynb](./examples/vector_similarity_search.ipynb).
-### Data Ingestion | @asl3 the readme changes are still here. |
pyspark-ai | github_2023 | others | 175 | pyspark-ai | gengliangwang | @@ -127,28 +127,6 @@ Now when you call df.ai.transform as before, the agent will use word embeddings
For a detailed walkthrough, please refer to our [vector_similarity_search.ipynb](./examples/vector_similarity_search.ipynb).
-### Data Ingestion
-If you have [set up the Google Python client](https://developers.google.com/docs/api/quickstart/python), you can ingest data via search engine:
-```python
-auto_df = spark_ai.create_df("2022 USA national auto sales by brand")
-```
-Otherwise, you can ingest data via URL:
-```python
-auto_df = spark_ai.create_df("https://www.carpro.com/blog/full-year-2022-national-auto-sales-by-brand")
-```
-
-Take a look at the data:
-```python
-auto_df.show(n=5)
-```
-| rank | brand | us_sales_2022 | sales_change_vs_2021 |
-|------|-----------|---------------|----------------------|
-| 1 | Toyota | 1849751 | -9 |
-| 2 | Ford | 1767439 | -2 |
-| 3 | Chevrolet | 1502389 | 6 |
-| 4 | Honda | 881201 | -33 |
-| 5 | Hyundai | 724265 | -2 |
-
### Plot
```python
auto_df.ai.plot() | Let's add one line for the creation of `auto_df`
e.g
```
# auto sales data from https://www.carpro.com/blog/full-year-2022-national-auto-sales-by-brand
data = [('Toyota', 1849751, -9), ('Ford', 1767439, -2), ('Chevrolet', 1502389, 6),
('Honda', 881201, -33), ('Hyundai', 724265, -2), ('Kia', 693549, -1),
('Jeep', 684612, -12), ('Nissan', 682731, -25), ('Subaru', 556581, -5),
('Ram Trucks', 545194, -16), ('GMC', 517649, 7), ('Mercedes-Benz', 350949, 7),
('BMW', 332388, -1), ('Volkswagen', 301069, -20), ('Mazda', 294908, -11),
('Lexus', 258704, -15), ('Dodge', 190793, -12), ('Audi', 186875, -5),
('Cadillac', 134726, 14), ('Chrysler', 112713, -2), ('Buick', 103519, -42),
('Acura', 102306, -35), ('Volvo', 102038, -16), ('Mitsubishi', 102037, -16),
('Lincoln', 83486, -4), ('Porsche', 70065, 0), ('Genesis', 56410, 14),
('INFINITI', 46619, -20), ('MINI', 29504, -1), ('Alfa Romeo', 12845, -30),
('Maserati', 6413, -10), ('Bentley', 3975, 0), ('Lamborghini', 3134, 3),
('Fiat', 915, -61), ('McLaren', 840, -35), ('Rolls-Royce', 460, 7)]
auto_df = spark.createDataFrame(data, ["Brand", "US_Sales_2022", "Sales_Change_Percentage"])
```
|
pyspark-ai | github_2023 | others | 175 | pyspark-ai | gengliangwang | @@ -127,30 +127,31 @@ Now when you call df.ai.transform as before, the agent will use word embeddings
For a detailed walkthrough, please refer to our [vector_similarity_search.ipynb](./examples/vector_similarity_search.ipynb).
-### Data Ingestion
-If you have [set up the Google Python client](https://developers.google.com/docs/api/quickstart/python), you can ingest data via search engine:
-```python
-auto_df = spark_ai.create_df("2022 USA national auto sales by brand")
-```
-Otherwise, you can ingest data via URL:
-```python
-auto_df = spark_ai.create_df("https://www.carpro.com/blog/full-year-2022-national-auto-sales-by-brand")
-```
+### Plot
+Let's create a DataFrame for car sales in the U.S.
-Take a look at the data:
```python
-auto_df.show(n=5)
+# auto sales data from https://www.carpro.com/blog/full-year-2022-national-auto-sales-by-brand
+data = [('Toyota', 1849751, -9), ('Ford', 1767439, -2), ('Chevrolet', 1502389, 6),
+ ('Honda', 881201, -33), ('Hyundai', 724265, -2), ('Kia', 693549, -1),
+ ('Jeep', 684612, -12), ('Nissan', 682731, -25), ('Subaru', 556581, -5),
+ ('Ram Trucks', 545194, -16), ('GMC', 517649, 7), ('Mercedes-Benz', 350949, 7),
+ ('BMW', 332388, -1), ('Volkswagen', 301069, -20), ('Mazda', 294908, -11),
+ ('Lexus', 258704, -15), ('Dodge', 190793, -12), ('Audi', 186875, -5),
+ ('Cadillac', 134726, 14), ('Chrysler', 112713, -2), ('Buick', 103519, -42),
+ ('Acura', 102306, -35), ('Volvo', 102038, -16), ('Mitsubishi', 102037, -16),
+ ('Lincoln', 83486, -4), ('Porsche', 70065, 0), ('Genesis', 56410, 14),
+ ('INFINITI', 46619, -20), ('MINI', 29504, -1), ('Alfa Romeo', 12845, -30),
+ ('Maserati', 6413, -10), ('Bentley', 3975, 0), ('Lamborghini', 3134, 3),
+ ('Fiat', 915, -61), ('McLaren', 840, -35), ('Rolls-Royce', 460, 7)]
+
+auto_df = spark.createDataFrame(data, ["Brand", "US_Sales_2022", "Sales_Change_Percentage"]) | where is `spark` from? We can create a new SparkSession |
pyspark-ai | github_2023 | python | 132 | pyspark-ai | gengliangwang | @@ -62,5 +62,25 @@ def test_multiple_sql_code_blocks(self):
self.assertEqual(AIUtils.extract_code_blocks(text), ["SELECT a FROM b;", "SELECT c FROM d;"])
+class TestRetryExecution(unittest.TestCase): | @xinrong-meng can we have a test case which mocks the response from LLM and generates bad code? |
pyspark-ai | github_2023 | python | 132 | pyspark-ai | gengliangwang | @@ -132,3 +132,17 @@ def extract_code_blocks(text: str) -> List[str]:
if text.startswith("`") and text.endswith("`"):
return [text.strip("`")]
return [text]
+
+ @staticmethod
+ def retry_execution(callback, max_tries=3):
+ tries = 0
+ last_exception = None
+ while max_tries > tries:
+ try:
+ return callback() | We need to have a conversation with LLM and feedback the error message |
pyspark-ai | github_2023 | python | 132 | pyspark-ai | gengliangwang | @@ -484,21 +484,30 @@ def explain_df(self, df: DataFrame, cache: bool = True) -> str:
def plot_df(
self, df: DataFrame, desc: Optional[str] = None, cache: bool = True
) -> None:
- instruction = f"The purpose of the plot: {desc}" if desc is not None else ""
tags = self._get_tags(cache)
- response = self._plot_chain.run(
- tags=tags,
- columns=self._get_df_schema(df),
- explain=self._get_df_explain(df, cache),
- instruction=instruction,
- )
- self.log(response)
- codeblocks = AIUtils.extract_code_blocks(response)
- code = "\n".join(codeblocks)
- try:
+
+ def callback(error_messages: List[str]):
+ accumulated_errors = "\n".join(error_messages)
+ instruction_base = (
+ f"The purpose of the plot: {desc}." if desc is not None else ""
+ )
+ instruction = (
+ f"{instruction_base}\nPlease avoid errors:\n{accumulated_errors}" | TBH I prefer a clean way as follows:
```
SystemMessage("you are an assistant on plotting...")
HumanMessage("plot 4 week moving average")
AIMessage("import pandas as pd...")
HumanMessage("Error:...")
AIMessage("....")
``` |
pyspark-ai | github_2023 | python | 171 | pyspark-ai | asl3 | @@ -205,6 +216,22 @@
prefix=SPARK_SQL_PREFIX,
)
+SQL_CHAIN_EXAMPLES = [
+ sql_question1 + f"\nAnswer:\n```{sql_answer1}```",
+ sql_question2 + f"\nAnswer:\n```{sql_answer2}```", | do we want to give it all 4 examples? |
pyspark-ai | github_2023 | python | 163 | pyspark-ai | gengliangwang | @@ -40,13 +40,85 @@
template=SQL_TEMPLATE,
)
-SPARK_SQL_EXAMPLES = [
+SPARK_SQL_EXAMPLES_NO_VECTOR_SEARCH = [
"""QUESTION: Given a Spark temp view `spark_ai_temp_view_14kjd0` with the following sample vals,
in the format (column_name: type, [sample_value_1, sample_value_2...]):
```
-(a: STRING, [Kongur Tagh, Grossglockner])
-(b: INT, [7649, 3798])
-(c: STRING, [China, Austria])
+(a: string, [Kongur Tagh, Grossglockner])
+(b: int, [7649, 3798])
+(c: string, [China, Austria])
+```
+Write a Spark SQL query to retrieve from view `spark_ai_temp_view_14kjd0`: Find the mountain located in Japan.
+Thought: The column names are non-descriptive, but from the sample values I see that column `a` contains mountains
+and column `c` contains countries. So, I will filter on column `c` for 'Japan' and column `a` for the mountain.
+I will use = rather than "like" in my SQL query because I need an exact match.
+Action: query_validation
+Action Input: SELECT `a` FROM `spark_ai_temp_view_14kjd0` WHERE `c` = 'Japan'
+Observation: OK
+Thought:I now know the final answer.
+Final Answer: SELECT `a` FROM `spark_ai_temp_view_14kjd0` WHERE `c` = 'Japan'"""
+ """QUESTION: Given a Spark temp view `spark_ai_temp_view_93bcf0` with the following columns: | We can store the common examples into variables to avoid duplicated code. So that in the future we don't need to modify two examples together. |
pyspark-ai | github_2023 | python | 163 | pyspark-ai | gengliangwang | @@ -40,13 +40,85 @@
template=SQL_TEMPLATE,
)
-SPARK_SQL_EXAMPLES = [
+SPARK_SQL_EXAMPLES_NO_VECTOR_SEARCH = [
"""QUESTION: Given a Spark temp view `spark_ai_temp_view_14kjd0` with the following sample vals,
in the format (column_name: type, [sample_value_1, sample_value_2...]):
```
-(a: STRING, [Kongur Tagh, Grossglockner])
-(b: INT, [7649, 3798])
-(c: STRING, [China, Austria])
+(a: string, [Kongur Tagh, Grossglockner])
+(b: int, [7649, 3798])
+(c: string, [China, Austria])
+```
+Write a Spark SQL query to retrieve from view `spark_ai_temp_view_14kjd0`: Find the mountain located in Japan.
+Thought: The column names are non-descriptive, but from the sample values I see that column `a` contains mountains
+and column `c` contains countries. So, I will filter on column `c` for 'Japan' and column `a` for the mountain.
+I will use = rather than "like" in my SQL query because I need an exact match.
+Action: query_validation
+Action Input: SELECT `a` FROM `spark_ai_temp_view_14kjd0` WHERE `c` = 'Japan'
+Observation: OK
+Thought:I now know the final answer.
+Final Answer: SELECT `a` FROM `spark_ai_temp_view_14kjd0` WHERE `c` = 'Japan'"""
+ """QUESTION: Given a Spark temp view `spark_ai_temp_view_93bcf0` with the following columns:
+```
+Product: string | we should unify the output here even when there area no sample values, comparing to
```
(a: string, [Kongur Tagh, Grossglockner])
(b: int, [7649, 3798])
(c: string, [China, Austria])
```
But we can do it in a follow-up PR |
pyspark-ai | github_2023 | python | 163 | pyspark-ai | gengliangwang | @@ -26,7 +26,10 @@ def _agent_type(self) -> str:
@classmethod
def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate:
"""Return default prompt."""
- return SPARK_SQL_PROMPT
+ if len(tools) == 2: | Shall we can whether SimilarValueTool in the tools instead? In the future there can be more tools |
pyspark-ai | github_2023 | python | 163 | pyspark-ai | gengliangwang | @@ -363,6 +364,44 @@ def test_vector_file_lru_store_prepopulated_files(self):
finally:
self.spark.sql(f"DROP TABLE IF EXISTS {table_name}")
+ @unittest.skipUnless(
+ os.environ.get("OPENAI_API_KEY") and os.environ["OPENAI_API_KEY"].strip() != "",
+ "OPENAI_API_KEY is not set",
+ )
+ def test_disable_similar_value_tool(self): | ```suggestion
def test_transform_without_similar_value_tool(self):
``` |
pyspark-ai | github_2023 | python | 163 | pyspark-ai | gengliangwang | @@ -98,43 +155,27 @@
Observation: OK
Thought: I now know the final answer.
Final Answer: SELECT COUNT(`Student`) FROM `spark_ai_temp_view_12qcl3` WHERE `Birthday` = '01-01-2006'"""
- """QUESTION: Given a Spark temp view `spark_ai_temp_view_wl2sdf` with the following columns:
-```
-PassengerId INT
-Survived INT
-Pclass INT
-Name STRING
-Sex STRING
-Age DOUBLE
-SibSp INT
-Parch INT
-Ticket STRING
-Fare DOUBLE
-Cabin STRING
-Embarked STRING
-```
-Write a Spark SQL query to retrieve from view `spark_ai_temp_view_wl2sdf`: What's the name of the oldest survived passenger?
-Thought: I will query the Name and Age columns, filtering by Survived and ordering by Age in descending order.
-Action: query_validation
-Action Input: SELECT Name, Age FROM spark_ai_temp_view_wl2sdf WHERE Survived = 1 ORDER BY Age DESC LIMIT 1
-Observation: OK
-Thought:I now know the final answer.
-Final Answer: SELECT Name, Age FROM spark_ai_temp_view_wl2sdf WHERE Survived = 1 ORDER BY Age DESC LIMIT 1"""
+
+SPARK_SQL_EXAMPLES_NO_VECTOR_SEARCH = [
+ spark_sql_no_vector_example_1,
+ spark_sql_shared_example_1,
+ spark_sql_no_vector_example_2,
+ spark_sql_shared_example_2,
]
-SPARK_SQL_SUFFIX = """\nQuestion: Given a Spark temp view `{view_name}` {comment}.
-The dataframe contains the column names and types in this format:
-column_name: type.
-It's very important to ONLY use the verbatim column names in your resulting SQL query.
+SPARK_SQL_EXAMPLES_VECTOR_SEARCH = [
+ spark_sql_vector_example_1, | Let's abstract the common parts of
* spark_sql_vector_example_1 & spark_sql_no_vector_example_1
* spark_sql_no_vector_example_2 & spark_sql_vector_example_2
into variables. |
pyspark-ai | github_2023 | others | 162 | pyspark-ai | gengliangwang | @@ -22,29 +22,43 @@ classifiers = [
]
[tool.poetry.dependencies]
+# default required dependencies
python = "^3.8.1"
pydantic = "^1.10.10"
-requests = "^2.31.0"
-tiktoken = "0.4.0"
-beautifulsoup4 = "^4.12.2"
openai = "^0.27.8"
langchain = ">=0.0.271,<0.1.0"
-pandas = ">=1.0.5"
pygments = "^2.15.1"
-google-api-python-client = "^2.90.0"
-chispa = "^0.9.2"
-grpcio = ">=1.56.0"
-plotly = "^5.15.0"
-pyarrow = ">=4.0.0"
-grpcio-status = ">=1.56.0"
-faiss-cpu = "^1.7.4"
-sentence-transformers = "^2.2.2"
-torch = ">=2.0.0, !=2.0.1"
-
-[tool.poetry.dev-dependencies]
+
+# optional dependencies, opted into by groups
+
+# dependencies for create
+requests = { version = "^2.31.0", optional = true }
+tiktoken = { version = "0.4.0", optional = true }
+beautifulsoup4 = { version = "^4.12.2", optional = true }
+google-api-python-client = { version = "^2.90.0", optional = true }
+
+# dependencies for plot
+pandas = { version = ">=1.0.5", optional = true, extras = ["all"]}
+grpcio = { version = ">=1.56.0", optional = true} | this one is for spark connect. We can have a group for spark connect. |
pyspark-ai | github_2023 | others | 162 | pyspark-ai | gengliangwang | @@ -22,29 +22,43 @@ classifiers = [
]
[tool.poetry.dependencies]
+# default required dependencies
python = "^3.8.1"
pydantic = "^1.10.10"
-requests = "^2.31.0"
-tiktoken = "0.4.0"
-beautifulsoup4 = "^4.12.2"
openai = "^0.27.8"
langchain = ">=0.0.271,<0.1.0"
-pandas = ">=1.0.5"
pygments = "^2.15.1"
-google-api-python-client = "^2.90.0"
-chispa = "^0.9.2"
-grpcio = ">=1.56.0"
-plotly = "^5.15.0"
-pyarrow = ">=4.0.0"
-grpcio-status = ">=1.56.0"
-faiss-cpu = "^1.7.4"
-sentence-transformers = "^2.2.2"
-torch = ">=2.0.0, !=2.0.1"
-
-[tool.poetry.dev-dependencies]
+
+# optional dependencies, opted into by groups
+
+# dependencies for create
+requests = { version = "^2.31.0", optional = true }
+tiktoken = { version = "0.4.0", optional = true }
+beautifulsoup4 = { version = "^4.12.2", optional = true }
+google-api-python-client = { version = "^2.90.0", optional = true }
+
+# dependencies for plot
+pandas = { version = ">=1.0.5", optional = true, extras = ["all"]}
+grpcio = { version = ">=1.56.0", optional = true}
+plotly = { version = "^5.15.0", optional = true }
+pyarrow = { version = ">=4.0.0", optional = true }
+
+# dependencies for vector-search
+grpcio-status = { version = ">=1.56.0", optional = true } | this one is for spark connect. We can have a group for spark connect. |
pyspark-ai | github_2023 | others | 162 | pyspark-ai | gengliangwang | @@ -22,29 +22,43 @@ classifiers = [
]
[tool.poetry.dependencies]
+# default required dependencies
python = "^3.8.1"
pydantic = "^1.10.10"
-requests = "^2.31.0"
-tiktoken = "0.4.0"
-beautifulsoup4 = "^4.12.2"
openai = "^0.27.8"
langchain = ">=0.0.271,<0.1.0"
-pandas = ">=1.0.5"
pygments = "^2.15.1"
-google-api-python-client = "^2.90.0"
-chispa = "^0.9.2"
-grpcio = ">=1.56.0"
-plotly = "^5.15.0"
-pyarrow = ">=4.0.0"
-grpcio-status = ">=1.56.0"
-faiss-cpu = "^1.7.4"
-sentence-transformers = "^2.2.2"
-torch = ">=2.0.0, !=2.0.1"
-
-[tool.poetry.dev-dependencies]
+
+# optional dependencies, opted into by groups
+
+# dependencies for create
+requests = { version = "^2.31.0", optional = true }
+tiktoken = { version = "0.4.0", optional = true }
+beautifulsoup4 = { version = "^4.12.2", optional = true }
+google-api-python-client = { version = "^2.90.0", optional = true }
+
+# dependencies for plot
+pandas = { version = ">=1.0.5", optional = true, extras = ["all"]}
+grpcio = { version = ">=1.56.0", optional = true}
+plotly = { version = "^5.15.0", optional = true }
+pyarrow = { version = ">=4.0.0", optional = true }
+
+# dependencies for vector-search
+grpcio-status = { version = ">=1.56.0", optional = true }
+faiss-cpu = { version = "^1.7.4", optional = true }
+sentence-transformers = { version = "^2.2.2", optional = true }
+torch = { version = ">=2.0.0, !=2.0.1", optional = true }
+
+[tool.poetry.group.dev.dependencies]
pyspark = "^3.4.0"
babel = "^2.12.1"
+chispa = "^0.9.2"
[tool.poetry.group.lint.dependencies]
flake8 = "^6.0.0"
black = "^23.7.0"
+
+[tool.poetry.extras]
+create = ["requests", "tiktoken", "beautifulsoup4", "google-api-python-client"] | let's rename it as ingestion |
pyspark-ai | github_2023 | others | 162 | pyspark-ai | gengliangwang | @@ -22,29 +22,43 @@ classifiers = [
]
[tool.poetry.dependencies]
+# default required dependencies
python = "^3.8.1"
pydantic = "^1.10.10"
-requests = "^2.31.0"
-tiktoken = "0.4.0"
-beautifulsoup4 = "^4.12.2"
openai = "^0.27.8"
langchain = ">=0.0.271,<0.1.0"
-pandas = ">=1.0.5"
pygments = "^2.15.1"
-google-api-python-client = "^2.90.0"
-chispa = "^0.9.2"
-grpcio = ">=1.56.0"
-plotly = "^5.15.0"
-pyarrow = ">=4.0.0"
-grpcio-status = ">=1.56.0"
-faiss-cpu = "^1.7.4"
-sentence-transformers = "^2.2.2"
-torch = ">=2.0.0, !=2.0.1"
-
-[tool.poetry.dev-dependencies]
+
+# optional dependencies, opted into by groups
+
+# dependencies for create
+requests = { version = "^2.31.0", optional = true } | This will be included in default too. I think we can have the following:
```
[tool.poetry.dependencies]
python = "^3.8.1"
pydantic = "^1.10.10"
openai = "^0.27.8"
langchain = ">=0.0.271,<0.1.0"
[tool.poetry.dependencies.plot]
pandas = ">=1.0.5"
plotly = "^5.15.0"
[tool.poetry.dependencies.vector-search]
faiss-cpu = "*"
sentence-transformers = "*"
torch = "*"
[tool.poetry.dependencies.ingestion]
requests = "^2.31.0"
tiktoken = "0.4.0"
beautifulsoup4 = "^4.12.2"
google-api-python-client = "^2.90.0"
[tool.poetry.dependencies.spark-connect]
grpcio = ">=1.56.0"
grpcio-status = ">=1.56.0"
pyarrow = ">=4.0.0"
[tool.poetry.extras]
plot = ["pandas", "plotly", "pyarrow"]
vector-search = ["faiss-cpu", "sentence-transformers", "torch"]
ingestion = ["requests", "tiktoken", "beautifulsoup4", "google-api-python-client"]
spark-connect = ["grpcio", "grpcio-status"]
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.