7zon-cli 0.2.4__tar.gz → 0.2.6__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/PKG-INFO +1 -1
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/pyproject.toml +1 -1
- 7zon_cli-0.2.6/src/zon7/__init__.py +1 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/cli.py +8 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/context.py +6 -1
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/prompts.py +1 -1
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/providers/gemini.py +41 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/safety.py +7 -2
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/shell.py +2 -1
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/tools.py +117 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_gemini.py +31 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_safety.py +22 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_tools.py +95 -0
- 7zon_cli-0.2.4/src/zon7/__init__.py +0 -1
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/.github/workflows/ci.yml +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/.github/workflows/publish.yml +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/.gitignore +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/LICENSE +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/README.md +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/install-termux.sh +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/__main__.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/ai.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/banner.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/common.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/config.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/instagram.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/memory.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/menu.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/providers/__init__.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/providers/claude.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/src/zon7/secrets.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_cli.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_config.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_context.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_instagram.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_memory.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_menu.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_powershell_real.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_secrets.py +0 -0
- {7zon_cli-0.2.4 → 7zon_cli-0.2.6}/tests/test_shell.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: 7zon-cli
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.6
|
|
4
4
|
Summary: 7ZON — terminalda ishlaydigan AI yordamchi: buyruq yozadi, xatolarni tuzatadi, tushuntiradi.
|
|
5
5
|
Project-URL: Homepage, https://github.com/7zon-uz/7ZON-CLI
|
|
6
6
|
Project-URL: Issues, https://github.com/7zon-uz/7ZON-CLI/issues
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.6"
|
|
@@ -269,6 +269,10 @@ def chat() -> None:
|
|
|
269
269
|
|
|
270
270
|
def _build_agent(cfg: dict, headless: bool = False, yolo: bool = False) -> tuple[Any, Any]:
|
|
271
271
|
runner = tools.ToolRunner(console, console.input, headless=headless)
|
|
272
|
+
if _gemini_key_available(cfg):
|
|
273
|
+
from zon7.providers import gemini as _gemini
|
|
274
|
+
|
|
275
|
+
runner.image_generator = lambda prompt, ratio: _gemini.generate_image(cfg, prompt, ratio)
|
|
272
276
|
runner.auto_approve = yolo
|
|
273
277
|
try:
|
|
274
278
|
tools.ToolRunner.prepare_workspace()
|
|
@@ -310,6 +314,10 @@ def _has_key(cfg: dict[str, Any]) -> bool:
|
|
|
310
314
|
return bool(config.clean_key(cfg.get(config.KEY_FIELDS.get(name, "")) or ""))
|
|
311
315
|
|
|
312
316
|
|
|
317
|
+
def _gemini_key_available(cfg: dict[str, Any]) -> bool:
|
|
318
|
+
return _has_key({**cfg, "provider": "gemini"})
|
|
319
|
+
|
|
320
|
+
|
|
313
321
|
def _is_set_key_line(line: str) -> bool:
|
|
314
322
|
"""Chat ichida yozilgan '7zon config set-key' yoki '/key' ni taniydi."""
|
|
315
323
|
words = line.strip().lower().split()
|
|
@@ -28,7 +28,12 @@ WINDOWS_NOTE = (
|
|
|
28
28
|
"Windows notes: commands run in PowerShell. Write PowerShell syntax, not bash: join commands with `;` "
|
|
29
29
|
"(Windows PowerShell 5.1 has no `&&`), use $env:NAME for environment variables, New-Item -ItemType Directory, "
|
|
30
30
|
"Get-ChildItem, Remove-Item, Copy-Item, Test-Path, Invoke-WebRequest; open links with `Start-Process URL`; "
|
|
31
|
-
"install software with `winget install --id ID -e --accept-source-agreements --accept-package-agreements`."
|
|
31
|
+
"install software with `winget install --id ID -e --accept-source-agreements --accept-package-agreements`. "
|
|
32
|
+
"Never pass code with quotes to `python -c` (Windows PowerShell strips the inner double quotes and the code "
|
|
33
|
+
"breaks): write the script with write_file into ~/.7zon/scripts and run it with `python PATH`. "
|
|
34
|
+
"The 7ZON venv's tools are in ~/.7zon/venv/Scripts (python.exe, pip.exe), not venv/bin. "
|
|
35
|
+
"Save files from the internet with the download_file tool. The Desktop path is "
|
|
36
|
+
"[Environment]::GetFolderPath('Desktop') (it can be inside OneDrive)."
|
|
32
37
|
)
|
|
33
38
|
|
|
34
39
|
|
|
@@ -44,7 +44,7 @@ You have tools: run_command (shell), read_file, write_file, edit_file (change pa
|
|
|
44
44
|
|
|
45
45
|
Working in a codebase: explore before changing. Use glob and grep (not shell find/grep) to locate code, read_file to read it, then edit_file for small changes. When the user shares a screenshot, design or PDF path, open it with view_file. When the user says "eslab qol" / "remember" or states a lasting preference, call save_memory. The user can undo your file changes with /undo. When the user asks you to do something on their computer (create a folder or project, write or edit files, run, build, install, use git, find files), do it yourself with the tools instead of telling them which commands to type. The user approves each command and file write, so just call the tool; do not ask "shall I run this?" in text first. Work step by step, check results (for example with list_directory or a quick command), and fix problems you hit.
|
|
46
46
|
|
|
47
|
-
Be proactive. Never answer "if you have X installed, you could..." — check yourself (for example `command -v gh`) and do the task. The user's computer usually has command-line tools that are already signed in: gh for GitHub (`gh repo list OWNER --limit 5 --json name,updatedAt,visibility`, `gh api ...`), git, docker, npm, cloud CLIs. For anything involving online accounts, use those existing sign-ins. To read a web page or a public API, use fetch_url. To search the web, use fetch_url with https://html.duckduckgo.com/html/?q=YOUR+QUERY and then open the best results.
|
|
47
|
+
Be proactive. Never answer "if you have X installed, you could..." — check yourself (for example `command -v gh`) and do the task. The user's computer usually has command-line tools that are already signed in: gh for GitHub (`gh repo list OWNER --limit 5 --json name,updatedAt,visibility`, `gh api ...`), git, docker, npm, cloud CLIs. For anything involving online accounts, use those existing sign-ins. To read a web page or a public API, use fetch_url. To search the web, use fetch_url with https://html.duckduckgo.com/html/?q=YOUR+QUERY and then open the best results. To save pictures or other files from the internet, use download_file. To make a new picture (logo, icon, banner, illustration, anything realistic, 3D or premium), use generate_image with a rich, specific prompt, then look at the result and improve it if needed; do not imitate such pictures with shapes drawn in Python, SVG or HTML. Never make up URLs of files, pictures or API endpoints: take them from a search, API answer or page you actually read; a guessed URL ends in 404.
|
|
48
48
|
|
|
49
49
|
Editing code: read the file first, then change only what is needed with edit_file (exact old text → new text); use write_file for new files or full rewrites. After changes, run the project's build or tests when there are any.
|
|
50
50
|
|
|
@@ -385,3 +385,44 @@ class Agent:
|
|
|
385
385
|
# Xato yoki Ctrl+C: tarixni so'rovdan oldingi holatga qaytaramiz
|
|
386
386
|
del self.contents[start:]
|
|
387
387
|
raise
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
# --------------------------------------------------------------------------- rasm yaratish
|
|
391
|
+
|
|
392
|
+
IMAGE_MODELS = ("gemini-3-pro-image", "gemini-3.1-flash-image", "gemini-2.5-flash-image")
|
|
393
|
+
BILLING_HINT = (
|
|
394
|
+
"Rasm yaratish Google'ning bepul tarifida yopiq (limit 0). Yoqish uchun: https://aistudio.google.com "
|
|
395
|
+
"→ Billing → loyihangizga to'lov kartasini ulang (har bir rasm pullik, narxi AI Studio'da ko'rsatiladi)."
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def generate_image(cfg: dict[str, Any], prompt: str, aspect_ratio: str = "1:1") -> tuple[bytes, str, str]:
|
|
400
|
+
"""Gemini rasm modeli bilan rasm yaratadi: (baytlar, mime, model). Eng sifatli modeldan boshlanadi."""
|
|
401
|
+
key = _api_key(cfg)
|
|
402
|
+
body = {
|
|
403
|
+
"contents": [{"role": "user", "parts": [{"text": prompt}]}],
|
|
404
|
+
"generationConfig": {"responseModalities": ["IMAGE", "TEXT"], "imageConfig": {"aspectRatio": aspect_ratio}},
|
|
405
|
+
}
|
|
406
|
+
quota_blocked = False
|
|
407
|
+
last: GeminiError | None = None
|
|
408
|
+
for model in IMAGE_MODELS:
|
|
409
|
+
try:
|
|
410
|
+
data = _http_post(f"{API_BASE}/{model}:generateContent", key, body)
|
|
411
|
+
except GeminiError as e:
|
|
412
|
+
last = e
|
|
413
|
+
if e.code == 429:
|
|
414
|
+
quota_blocked = True
|
|
415
|
+
continue
|
|
416
|
+
if e.code in (404, 500, 502, 503, 504):
|
|
417
|
+
continue
|
|
418
|
+
raise
|
|
419
|
+
for cand in data.get("candidates", []):
|
|
420
|
+
for part in (cand.get("content") or {}).get("parts", []):
|
|
421
|
+
inline = part.get("inlineData")
|
|
422
|
+
if inline and inline.get("data"):
|
|
423
|
+
return base64.b64decode(inline["data"]), inline.get("mimeType", "image/png"), model
|
|
424
|
+
reason = (data.get("candidates") or [{}])[0].get("finishReason", "") or "sabab noma'lum"
|
|
425
|
+
raise AIError(f"Model rasm qaytarmadi ({reason}). So'rovni boshqacha yozib ko'ring.")
|
|
426
|
+
if quota_blocked:
|
|
427
|
+
raise AIError(BILLING_HINT)
|
|
428
|
+
raise AIError(f"Rasm yaratib bo'lmadi: {last}")
|
|
@@ -28,13 +28,15 @@ CAUTION_PATTERNS = [
|
|
|
28
28
|
(r"\bkill(all)?\b|\bpkill\b", "jarayonlarni to'xtatadi"),
|
|
29
29
|
(r"\bchmod\b|\bchown\b", "ruxsatlarni o'zgartiradi"),
|
|
30
30
|
(r"\bmv\b", "fayllarni ko'chiradi yoki ustidan yozadi"),
|
|
31
|
-
(r"(^|[
|
|
31
|
+
(r"(^|[^>=\-])>(?![>=])\s*\S", "faylning ustidan yozadi"),
|
|
32
32
|
(r"\b(npm|pnpm|yarn|pip|brew|apt(-get)?|dnf|pacman)\s+(uninstall|remove|purge)\b", "paketni o'chiradi"),
|
|
33
33
|
(r"\bdocker\s+(system\s+prune|rm|rmi|volume\s+rm)\b", "Docker resurslarini o'chiradi"),
|
|
34
34
|
(r"\bgit\s+(clean|checkout\s+--|restore)\b", "lokal o'zgarishlarni bekor qiladi"),
|
|
35
35
|
]
|
|
36
36
|
|
|
37
37
|
|
|
38
|
+
REDIRECT_PATTERN = CAUTION_PATTERNS[5][0]
|
|
39
|
+
QUOTED = re.compile(r"'[^']*'|\"(?:[^\"\\]|\\.)*\"")
|
|
38
40
|
HARMLESS_REDIRECTS = re.compile(r"(\d*|&)>>?\s*/dev/null\b|\d*>&\d+|<\s*/dev/null\b")
|
|
39
41
|
|
|
40
42
|
|
|
@@ -48,8 +50,11 @@ def assess(command: str) -> tuple[str, list[str]]:
|
|
|
48
50
|
return "danger", reasons
|
|
49
51
|
# Zararsiz yo'naltirishlar (chiqishni yashirish, stderr→stdout) faylni o'zgartirmaydi
|
|
50
52
|
harmless = HARMLESS_REDIRECTS.sub(" ", command)
|
|
53
|
+
# Qo'shtirnoq ichidagi matn (masalan, python -c '...' kodi) yo'naltirish emas: "a > b" taqqoslash, "->" strelka
|
|
54
|
+
unquoted = QUOTED.sub("''", harmless)
|
|
51
55
|
for pattern, reason in CAUTION_PATTERNS:
|
|
52
|
-
if
|
|
56
|
+
text = unquoted if pattern == REDIRECT_PATTERN else harmless
|
|
57
|
+
if re.search(pattern, text, re.IGNORECASE):
|
|
53
58
|
reasons.append(reason)
|
|
54
59
|
return ("caution" if reasons else "safe"), reasons
|
|
55
60
|
|
|
@@ -42,7 +42,8 @@ def argv(command: str, marker: str | None = None, interactive: bool = False, ps:
|
|
|
42
42
|
# UTF-8 chiqish va rang kodlarisiz oddiy matn (PowerShell 7.2+ da $PSStyle bor)
|
|
43
43
|
script = ("[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
|
|
44
44
|
"$OutputEncoding = [System.Text.Encoding]::UTF8; "
|
|
45
|
-
"if ($PSStyle) { $PSStyle.OutputRendering = 'PlainText' }
|
|
45
|
+
"if ($PSStyle) { $PSStyle.OutputRendering = 'PlainText' }; "
|
|
46
|
+
"$PSNativeCommandArgumentPassing = 'Standard'\n" + command)
|
|
46
47
|
if marker:
|
|
47
48
|
script += (
|
|
48
49
|
"\n$__7zon_ok = $?"
|
|
@@ -24,6 +24,7 @@ from rich.syntax import Syntax
|
|
|
24
24
|
from zon7 import instagram as ig
|
|
25
25
|
from zon7 import memory, menu, safety, shell
|
|
26
26
|
from zon7 import secrets as vault
|
|
27
|
+
from zon7.common import AIError
|
|
27
28
|
|
|
28
29
|
MAX_OUTPUT_CHARS = 20_000
|
|
29
30
|
MAX_READ_BYTES = 200_000
|
|
@@ -36,6 +37,8 @@ MAX_ATTACH_BYTES = 15_000_000
|
|
|
36
37
|
VIEWABLE = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
|
|
37
38
|
".webp": "image/webp", ".pdf": "application/pdf"}
|
|
38
39
|
FETCH_TIMEOUT = 20
|
|
40
|
+
DOWNLOAD_TIMEOUT = 60
|
|
41
|
+
MAX_DOWNLOAD_BYTES = 100_000_000
|
|
39
42
|
CWD_MARKER = "__7ZON_CWD__"
|
|
40
43
|
# Rang va kursor kodlari: ekranda axlat bo'lib ko'rinmasin va AI'ga bormasin
|
|
41
44
|
ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(\x07|\x1b\\)")
|
|
@@ -170,6 +173,48 @@ TOOL_SPECS: list[dict[str, Any]] = [
|
|
|
170
173
|
"additionalProperties": False,
|
|
171
174
|
},
|
|
172
175
|
},
|
|
176
|
+
{
|
|
177
|
+
"name": "download_file",
|
|
178
|
+
"description": (
|
|
179
|
+
"Save a file from a public URL (picture, PDF, archive, dataset) to a path on disk. Creates missing "
|
|
180
|
+
"folders. Use only URLs you got from a tool result (an API answer or a page you read); never guess "
|
|
181
|
+
"or make up file URLs. For pictures of a topic use the Wikimedia Commons API with fetch_url first: "
|
|
182
|
+
"https://commons.wikimedia.org/w/api.php?action=query&generator=search&gsrsearch=QUERY&gsrnamespace=6"
|
|
183
|
+
"&gsrlimit=20&prop=imageinfo&iiprop=url|mime&iiurlwidth=1280&format=json and then download each "
|
|
184
|
+
"imageinfo thumburl (or url). Check the returned content_type; HTML means it was not the file."
|
|
185
|
+
),
|
|
186
|
+
"parameters": {
|
|
187
|
+
"type": "object",
|
|
188
|
+
"properties": {
|
|
189
|
+
"url": {"type": "string", "description": "Direct http(s) URL of the file."},
|
|
190
|
+
"path": {"type": "string", "description": "Where to save it, e.g. ~/Desktop/folder/photo1.jpg"},
|
|
191
|
+
},
|
|
192
|
+
"required": ["url", "path"],
|
|
193
|
+
"additionalProperties": False,
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
{
|
|
197
|
+
"name": "generate_image",
|
|
198
|
+
"description": (
|
|
199
|
+
"Create a new picture with an image-generation AI and save it: logos, icons, illustrations, banners, "
|
|
200
|
+
"photorealistic or 3D renders. Use it whenever the user wants a picture to be made (a logo, a "
|
|
201
|
+
"premium/3D/realistic image); never draw such pictures with code shapes. Write a detailed English "
|
|
202
|
+
"prompt: subject, style (e.g. photorealistic 3D render, PBR materials, studio lighting, soft shadows, "
|
|
203
|
+
"reflections), colours, composition, background, and the exact text to show in quotes. After saving, "
|
|
204
|
+
"look at the result (it is attached for you) and regenerate with a better prompt if it is not good."
|
|
205
|
+
),
|
|
206
|
+
"parameters": {
|
|
207
|
+
"type": "object",
|
|
208
|
+
"properties": {
|
|
209
|
+
"prompt": {"type": "string", "description": "Detailed English description of the picture."},
|
|
210
|
+
"path": {"type": "string", "description": "Where to save, e.g. ~/Desktop/app/logo.png"},
|
|
211
|
+
"aspect_ratio": {"type": "string", "enum": ["1:1", "16:9", "9:16", "4:3", "3:4"],
|
|
212
|
+
"description": "1:1 for logos and icons."},
|
|
213
|
+
},
|
|
214
|
+
"required": ["prompt", "path", "aspect_ratio"],
|
|
215
|
+
"additionalProperties": False,
|
|
216
|
+
},
|
|
217
|
+
},
|
|
173
218
|
{
|
|
174
219
|
"name": "glob",
|
|
175
220
|
"description": (
|
|
@@ -278,6 +323,8 @@ class ToolRunner:
|
|
|
278
323
|
self.attachments: list[tuple[str, bytes, str]] = [] # (mime, baytlar, yo'l) — model ko'radigan fayllar
|
|
279
324
|
self.instagram_http: Any = ig.default_http # testlarda almashtiriladi
|
|
280
325
|
self.temp_upload: Any = ig.upload_temp
|
|
326
|
+
# (prompt, nisbat) -> (baytlar, mime, model); cli Gemini kaliti bilan ulaydi
|
|
327
|
+
self.image_generator: Callable[[str, str], tuple[bytes, str, str]] | None = None
|
|
281
328
|
|
|
282
329
|
@staticmethod
|
|
283
330
|
def prepare_workspace(home: Path | None = None) -> Path:
|
|
@@ -294,6 +341,9 @@ class ToolRunner:
|
|
|
294
341
|
|
|
295
342
|
def _env(self) -> dict[str, str]:
|
|
296
343
|
env = dict(os.environ)
|
|
344
|
+
# Windows'da Python skriptlari emoji/o'zbekcha matnni cp1251 bilan chiqara olmay yiqiladi
|
|
345
|
+
env.setdefault("PYTHONIOENCODING", "utf-8")
|
|
346
|
+
env.setdefault("PYTHONUTF8", "1")
|
|
297
347
|
env.update(self.secrets)
|
|
298
348
|
return env
|
|
299
349
|
|
|
@@ -355,6 +405,8 @@ class ToolRunner:
|
|
|
355
405
|
"write_file": self.write_file,
|
|
356
406
|
"list_directory": self.list_directory,
|
|
357
407
|
"fetch_url": self.fetch_url,
|
|
408
|
+
"download_file": self.download_file,
|
|
409
|
+
"generate_image": self.generate_image,
|
|
358
410
|
"edit_file": self.edit_file,
|
|
359
411
|
"request_secret": self.request_secret,
|
|
360
412
|
"instagram": self.instagram,
|
|
@@ -548,6 +600,71 @@ class ToolRunner:
|
|
|
548
600
|
self.console.print(f"[dim]📁 ko'rildi: {target}[/]")
|
|
549
601
|
return {"path": str(target), "entries": entries}
|
|
550
602
|
|
|
603
|
+
def generate_image(self, prompt: str, path: str, aspect_ratio: str = "1:1") -> dict[str, Any]:
|
|
604
|
+
if self.image_generator is None:
|
|
605
|
+
return {"error": "Image generation needs a Gemini API key (7zon config set-key --provider gemini)."}
|
|
606
|
+
target = self._path(path)
|
|
607
|
+
mime_ext = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
|
|
608
|
+
exists = target.exists()
|
|
609
|
+
self.console.print(f"[bold]🎨 Rasm yaratish:[/] {target}\n[dim]{prompt[:300]}[/]")
|
|
610
|
+
if not self._confirm("caution" if exists else "safe"):
|
|
611
|
+
return {"declined": True, "message": "The user declined image generation."}
|
|
612
|
+
try:
|
|
613
|
+
with self.console.status("[dim]Rasm chizilmoqda (20–60 soniya)...[/]", spinner="dots"):
|
|
614
|
+
data, mime, model = self.image_generator(prompt, aspect_ratio)
|
|
615
|
+
except AIError as e:
|
|
616
|
+
self.console.print(f"[red]✗ {e}[/]")
|
|
617
|
+
return {"error": str(e), "note": "Tell the user this reason plainly. Do not fake the picture with code shapes "
|
|
618
|
+
"and call it realistic; you may offer a simple code-drawn version only if the user wants it."}
|
|
619
|
+
ext = mime_ext.get(mime)
|
|
620
|
+
if ext and target.suffix.lower() not in mime_ext.values():
|
|
621
|
+
target = target.with_suffix(ext)
|
|
622
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
623
|
+
if target.exists():
|
|
624
|
+
self._checkpoint(target)
|
|
625
|
+
target.write_bytes(data)
|
|
626
|
+
self.attachments.append((mime, data, str(target))) # model natijani ko'rib baholaydi
|
|
627
|
+
self.console.print(f"[green]✓ saqlandi[/] [dim]{len(data) // 1024} KB[/]")
|
|
628
|
+
return {"saved": str(target), "bytes": len(data), "mime": mime,
|
|
629
|
+
"note": "The image is attached; check it matches the request before reporting."}
|
|
630
|
+
|
|
631
|
+
def download_file(self, url: str, path: str) -> dict[str, Any]:
|
|
632
|
+
url = url.strip()
|
|
633
|
+
if not re.match(r"^https?://", url, re.IGNORECASE):
|
|
634
|
+
return {"error": "Only http(s) URLs are supported."}
|
|
635
|
+
target = self._path(path)
|
|
636
|
+
exists = target.exists()
|
|
637
|
+
self.console.print(f"[bold]⬇️ Yuklab olish:[/] [cyan]{url}[/]\n → {target}")
|
|
638
|
+
if exists:
|
|
639
|
+
self.console.print("[yellow]⚠ bu fayl bor, ustidan yoziladi[/]")
|
|
640
|
+
if not self._confirm("caution" if exists else "safe"):
|
|
641
|
+
return {"declined": True, "message": "The user declined this download."}
|
|
642
|
+
request = urllib.request.Request(url, headers={
|
|
643
|
+
# Wikimedia kabi saytlar tushunarli User-Agent talab qiladi
|
|
644
|
+
"User-Agent": "7zon-cli/1.0 (https://github.com/7zon-uz/7ZON-CLI)", "Accept": "*/*"})
|
|
645
|
+
try:
|
|
646
|
+
with urllib.request.urlopen(request, timeout=DOWNLOAD_TIMEOUT) as resp:
|
|
647
|
+
data = resp.read(MAX_DOWNLOAD_BYTES + 1)
|
|
648
|
+
ctype = resp.headers.get("Content-Type", "")
|
|
649
|
+
except urllib.error.HTTPError as e:
|
|
650
|
+
msg = "HTTP 404: this URL does not exist; get real URLs from an API or page first" if e.code == 404 \
|
|
651
|
+
else f"HTTP {e.code}"
|
|
652
|
+
self.console.print(f"[red]✗ {msg.split(':')[0]}[/]")
|
|
653
|
+
return {"error": msg}
|
|
654
|
+
except (urllib.error.URLError, TimeoutError) as e:
|
|
655
|
+
return {"error": f"Could not open URL: {getattr(e, 'reason', e)}"}
|
|
656
|
+
if len(data) > MAX_DOWNLOAD_BYTES:
|
|
657
|
+
return {"error": f"File is larger than {MAX_DOWNLOAD_BYTES // 1_000_000} MB; download it with a command."}
|
|
658
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
659
|
+
if exists:
|
|
660
|
+
self._checkpoint(target)
|
|
661
|
+
target.write_bytes(data)
|
|
662
|
+
self.console.print(f"[green]✓ saqlandi[/] [dim]{len(data) // 1024} KB, {ctype or '?'}[/]")
|
|
663
|
+
result: dict[str, Any] = {"saved": str(target), "bytes": len(data), "content_type": ctype}
|
|
664
|
+
if "html" in ctype.lower():
|
|
665
|
+
result["warning"] = "The server returned an HTML page, not the file. Use a direct file URL."
|
|
666
|
+
return result
|
|
667
|
+
|
|
551
668
|
def fetch_url(self, url: str) -> dict[str, Any]:
|
|
552
669
|
url = url.strip()
|
|
553
670
|
if not re.match(r"^https?://", url, re.IGNORECASE):
|
|
@@ -219,3 +219,34 @@ def test_html_400_means_bad_key():
|
|
|
219
219
|
with pytest.raises(AIError, match="/key"):
|
|
220
220
|
with gemini.friendly_errors():
|
|
221
221
|
raise gemini.GeminiError(400, "", "<html><title>Error 400 (Bad Request)!!1</title></html> []")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def test_generate_image_falls_back_and_reports_billing(monkeypatch):
|
|
225
|
+
from zon7.common import AIError
|
|
226
|
+
from zon7.providers import gemini
|
|
227
|
+
|
|
228
|
+
tried = []
|
|
229
|
+
|
|
230
|
+
def fake_post(url, key, body, stream=False):
|
|
231
|
+
tried.append(url.rsplit("/", 1)[1])
|
|
232
|
+
raise gemini.GeminiError(429, "RESOURCE_EXHAUSTED", "quota")
|
|
233
|
+
|
|
234
|
+
monkeypatch.setattr(gemini, "_http_post", fake_post)
|
|
235
|
+
with pytest.raises(AIError, match="Billing"):
|
|
236
|
+
gemini.generate_image({"gemini_api_key": "k" * 30}, "logo")
|
|
237
|
+
assert len(tried) == len(gemini.IMAGE_MODELS)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def test_generate_image_returns_bytes(monkeypatch):
|
|
241
|
+
import base64
|
|
242
|
+
|
|
243
|
+
from zon7.providers import gemini
|
|
244
|
+
|
|
245
|
+
def fake_post(url, key, body, stream=False):
|
|
246
|
+
assert body["generationConfig"]["imageConfig"]["aspectRatio"] == "16:9"
|
|
247
|
+
return {"candidates": [{"content": {"parts": [{"text": "ok"}, {"inlineData": {
|
|
248
|
+
"mimeType": "image/png", "data": base64.b64encode(b"IMG").decode()}}]}}]}
|
|
249
|
+
|
|
250
|
+
monkeypatch.setattr(gemini, "_http_post", fake_post)
|
|
251
|
+
assert gemini.generate_image({"gemini_api_key": "k" * 30}, "logo", "16:9") == (b"IMG", "image/png",
|
|
252
|
+
gemini.IMAGE_MODELS[0])
|
|
@@ -62,3 +62,25 @@ def test_harmless_redirects_are_safe(cmd):
|
|
|
62
62
|
|
|
63
63
|
def test_real_overwrite_still_caution():
|
|
64
64
|
assert assess("echo x > /dev/null; echo y > notes.txt")[0] == "caution"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# ---------------------------------------------------------------- qo'shtirnoq ichidagi ">" yo'naltirish emas
|
|
68
|
+
|
|
69
|
+
def test_python_code_with_arrow_and_comparison_is_not_overwrite():
|
|
70
|
+
from zon7 import safety
|
|
71
|
+
|
|
72
|
+
cmd = """python -c 'print(f"Downloading {u} -> {p}")\nif count > 6: pass'"""
|
|
73
|
+
assert "faylning ustidan yozadi" not in safety.assess(cmd)[1]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_real_redirect_still_flagged():
|
|
77
|
+
from zon7 import safety
|
|
78
|
+
|
|
79
|
+
assert "faylning ustidan yozadi" in safety.assess("echo salom > notes.txt")[1]
|
|
80
|
+
assert "faylning ustidan yozadi" in safety.assess('echo "a > b" > out.txt')[1]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_powershell_arrow_ops_not_flagged():
|
|
84
|
+
from zon7 import safety
|
|
85
|
+
|
|
86
|
+
assert safety.assess("Get-Process | Where-Object { $_.CPU -gt 10 }")[0] == "safe"
|
|
@@ -338,3 +338,98 @@ def test_edit_preserves_line_endings(tmp_path):
|
|
|
338
338
|
assert crlf.read_bytes() == b"a\r\nB\r\nc\r\n"
|
|
339
339
|
runner("write_file", {"path": "new.txt", "content": "x\ny\n"})
|
|
340
340
|
assert (tmp_path / "new.txt").read_bytes() == b"x\ny\n"
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
# ---------------------------------------------------------------- download_file
|
|
344
|
+
|
|
345
|
+
import http.server # noqa: E402
|
|
346
|
+
import threading # noqa: E402
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@pytest.fixture
|
|
350
|
+
def file_server():
|
|
351
|
+
class Handler(http.server.BaseHTTPRequestHandler):
|
|
352
|
+
def do_GET(self): # noqa: N802
|
|
353
|
+
if self.path == "/pic.jpg":
|
|
354
|
+
body, ctype = b"\xff\xd8\xff" + b"0" * 2048, "image/jpeg"
|
|
355
|
+
elif self.path == "/page":
|
|
356
|
+
body, ctype = b"<html>hi</html>", "text/html"
|
|
357
|
+
else:
|
|
358
|
+
self.send_response(404)
|
|
359
|
+
self.end_headers()
|
|
360
|
+
return
|
|
361
|
+
self.send_response(200)
|
|
362
|
+
self.send_header("Content-Type", ctype)
|
|
363
|
+
self.send_header("Content-Length", str(len(body)))
|
|
364
|
+
self.end_headers()
|
|
365
|
+
self.wfile.write(body)
|
|
366
|
+
|
|
367
|
+
def log_message(self, *a):
|
|
368
|
+
pass
|
|
369
|
+
|
|
370
|
+
srv = http.server.HTTPServer(("127.0.0.1", 0), Handler)
|
|
371
|
+
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
372
|
+
yield f"http://127.0.0.1:{srv.server_port}"
|
|
373
|
+
srv.shutdown()
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def test_download_file_saves_into_new_folder(tmp_path, file_server):
|
|
377
|
+
r = make_runner(tmp_path, ["y"])
|
|
378
|
+
out = r("download_file", {"url": f"{file_server}/pic.jpg", "path": "rasul damas/damas_1.jpg"})
|
|
379
|
+
saved = tmp_path / "rasul damas" / "damas_1.jpg"
|
|
380
|
+
assert out["saved"] == str(saved.resolve())
|
|
381
|
+
assert saved.read_bytes().startswith(b"\xff\xd8\xff")
|
|
382
|
+
assert out["content_type"] == "image/jpeg"
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def test_download_file_404_says_url_is_made_up(tmp_path, file_server):
|
|
386
|
+
r = make_runner(tmp_path, ["y"])
|
|
387
|
+
out = r("download_file", {"url": f"{file_server}/nope.jpg", "path": "x.jpg"})
|
|
388
|
+
assert "404" in out["error"] and "real URLs" in out["error"]
|
|
389
|
+
assert not (tmp_path / "x.jpg").exists()
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def test_download_file_warns_on_html(tmp_path, file_server):
|
|
393
|
+
r = make_runner(tmp_path, ["y"])
|
|
394
|
+
out = r("download_file", {"url": f"{file_server}/page", "path": "p.jpg"})
|
|
395
|
+
assert "warning" in out
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def test_child_python_gets_utf8(tmp_path):
|
|
399
|
+
r = make_runner(tmp_path, [])
|
|
400
|
+
env = r._env()
|
|
401
|
+
assert env["PYTHONIOENCODING"] == "utf-8" and env["PYTHONUTF8"] == "1"
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
# ---------------------------------------------------------------- generate_image
|
|
405
|
+
|
|
406
|
+
def test_generate_image_saves_and_attaches(tmp_path):
|
|
407
|
+
r = make_runner(tmp_path, ["y"])
|
|
408
|
+
calls = []
|
|
409
|
+
r.image_generator = lambda prompt, ratio: calls.append((prompt, ratio)) or (b"\x89PNG fake", "image/png", "m")
|
|
410
|
+
out = r("generate_image", {"prompt": "premium 3D logo", "path": "app/logo", "aspect_ratio": "1:1"})
|
|
411
|
+
saved = tmp_path / "app" / "logo.png"
|
|
412
|
+
assert out["saved"] == str(saved.resolve())
|
|
413
|
+
assert saved.read_bytes() == b"\x89PNG fake"
|
|
414
|
+
assert calls == [("premium 3D logo", "1:1")]
|
|
415
|
+
assert r.pop_attachments()[0][0] == "image/png"
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def test_generate_image_billing_error_is_reported(tmp_path):
|
|
419
|
+
from zon7.common import AIError
|
|
420
|
+
|
|
421
|
+
r = make_runner(tmp_path, ["y"])
|
|
422
|
+
|
|
423
|
+
def blocked(prompt, ratio):
|
|
424
|
+
raise AIError("Rasm yaratish Google'ning bepul tarifida yopiq")
|
|
425
|
+
|
|
426
|
+
r.image_generator = blocked
|
|
427
|
+
out = r("generate_image", {"prompt": "x", "path": "logo.png", "aspect_ratio": "1:1"})
|
|
428
|
+
assert "bepul tarifida" in out["error"]
|
|
429
|
+
assert not (tmp_path / "logo.png").exists()
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def test_generate_image_without_key(tmp_path):
|
|
433
|
+
r = make_runner(tmp_path, [])
|
|
434
|
+
out = r("generate_image", {"prompt": "x", "path": "logo.png", "aspect_ratio": "1:1"})
|
|
435
|
+
assert "Gemini API key" in out["error"]
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.2.4"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|