Skip to main content

G4F-like OpenAI compatible wrapper for Perchance AI generators

Project description

Perchancy 🚀

PyPI version License: MIT

Perchancy is a high-speed, thread-safe, OpenAI-compatible Python wrapper for Perchance AI generators. Generate text and images programmatically with absolute zero manual browser management, bypassing anti-bot protections automatically.


✨ Key Features

  • ⚡ Blazing Fast Extraction: Deep iframe search & Regex-based DOM scanning for instant text and image extraction without timeouts.
  • 🧵 Thread-Safe Concurrency: Run multiple generators safely. Features a built-in queue system via max_concurrent_tabs to prevent browser crashes.
  • 🖼️ On-the-Fly Image Conversion: Automatically converts base64 blobs into desired formats (png, jpeg, webp) directly inside the browser engine.
  • 🛡️ Built-in Anti-Bot Bypass: Uses a pristine automated stealth environment. Defeats Cloudflare and invisible pop-ups automatically.
  • 🌍 Auto-Translation: Built-in Google Translate support for prompt/response.
  • 🌐 Integrated VPN Support: Pass VLESS links and the library sets up Xray-core automatically.

📦 Installation

To automatically install all dependencies required for the engine, run the included script:

python install.py

Alternatively, install manually via pip:

pip install DrissionPage requests

🚀 Quick Start

Text Generation (Synchronous)

import perchancy

client = perchancy.Client(headless=True)

response = client.chat.completions.create(
    model="ai-text-generator",
    messages=[{"role": "user", "content": "Write a 3-sentence horror story."}],
    stream=False,
    translation="auto"
)

content = response["choices"][0]["message"]["content"]
print(content)

Text Generation (Streaming)

import perchancy
import sys

client = perchancy.Client(headless=True)

response = client.chat.completions.create(
    model="ai-character-chat",
    messages=[{"role": "user", "content": "Tell me a short sci-fi intro."}],
    stream=True
)

for chunk in response:
    content = chunk["choices"][0]["delta"].get("content", "")
    sys.stdout.write(content)
    sys.stdout.flush()

Image Generation

import perchancy
import base64
import threading

client = perchancy.Client(headless=True, max_concurrent_tabs=4)

def run_image_task(thread_id, fmt):
    response = client.images.generate(
        model="ai-text-to-image-generator",
        prompt="cyberpunk city, neon lights",
        num_images=1,
        image_format=fmt,
        disable_safety_settings=True
    )

    for i, img in enumerate(response.get("data",[])):
        file_name = f"out_t{thread_id}_{i}.{fmt}"
        with open(file_name, "wb") as f:
            f.write(base64.b64decode(img["url"]))

t1 = threading.Thread(target=run_image_task, args=(1, "png"))
t2 = threading.Thread(target=run_image_task, args=(2, "jpeg"))

t1.start()
t2.start()

t1.join()
t2.join()

📚 API Documentation

Client Configuration

perchancy.Client(**kwargs) initializes the main browser engine.

Parameter Type Default Description
headless bool True Runs the browser in the background without a UI.
debug bool False Prints detailed execution status logs to the console.
max_concurrent_tabs int 4 Maximum number of active tabs allowed at the same time. Extra threads will wait in a queue.
vpn_configs List[str] None A list of VLESS/Proxy URIs for connection rotation.

Chat Completions

client.chat.completions.create(**kwargs)

Parameter Type Default Description
model str Required The URL slug of the Perchance generator (e.g., ai-character-chat).
messages List[Dict] Required Standard OpenAI messages array. Uses the content of the last message as the prompt.
stream bool False Returns a generator yielding text chunks as they are generated.
translation str None Translates the final output. Set to "auto" to translate back to the prompt's detected language.

Image Generation Parameters

client.images.generate(**kwargs)

Parameter Type Default Description
model str Required The URL slug of the generator.
prompt str Required The text description for the image generation.
num_images int 1 Number of images to generate in the current task.
image_format str "png" Target output format (png, jpeg, webp). Conversions happen automatically.
time_for_image int 90 Maximum wait time per image in seconds. Calculates time * num_images. Set to 0 for infinite.
disable_safety_settings bool False Attempts to bypass strict NSFW filters. Returns an error if blocked when False.

🛠 Advanced Features

Custom Parameters & Selectors

Perchance generators often have sliders or dropdowns (like seed, guidanceScale). You can control these using extra_params and param_mappings directly in the create or generate methods.

If the generator layout is non-standard, you can override the default CSS selectors via input_selectors, button_selectors, and output_selectors.

client.images.generate(
    model="ai-text-to-image-generator",
    prompt="A magical forest",
    extra_params={
        "guidanceScale": "7.5",
        "negativePrompt": "low quality, blurry"
    },
    param_mappings={
        "quality":["#resolution-dropdown-id", "[data-name='qualitySelect']"]
    },
    quality="high"
)

VPN & VLESS Proxy Rotation (EXPERIMENTAL)

⚠️ WARNING: The VPN and proxy rotation feature has only been superficially tested. You may encounter unexpected bugs, routing issues, or failures when using proxy lists. Use with caution.

You can pass a list of VLESS links or proxy configurations to the Client. The library will automatically rotate them on a per-request basis. If it's the first time running a VLESS proxy, it will prompt you to download Xray-core locally to handle the protocol.

Pass "disabled" inside the list to occasionally route traffic without a proxy.

import perchancy

vpn_list =[
    "disabled",
    "vless://uuid@server:port?type=ws&security=tls#Proxy1",
    "vless://uuid@server:port?type=tcp&security=reality#Proxy2"
]

client = perchancy.Client(vpn_configs=vpn_list)

client.images.generate(
    model="ai-text-to-image-generator",
    prompt="Testing VPN connection"
)

⚠️ Disclaimer

Unofficial wrapper. Use for educational purposes only. The author is not responsible for any misuse, account bans, or IP blocks.

📝 License

MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

perchancy-0.1.3.tar.gz (19.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

perchancy-0.1.3-py3-none-any.whl (17.7 kB view details)

Uploaded Python 3

File details

Details for the file perchancy-0.1.3.tar.gz.

File metadata

  • Download URL: perchancy-0.1.3.tar.gz
  • Upload date:
  • Size: 19.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for perchancy-0.1.3.tar.gz
Algorithm Hash digest
SHA256 c1ea9b75b95868d32804e78cf772a285683274d9e0c1ef7e4680f3029d8d2219
MD5 990f2e725b7e0032dd29122b8d4a6dcc
BLAKE2b-256 b5cf4411f5990cabc353b56836403fa06a9b106a09e7de1a4edec4782be8e64c

See more details on using hashes here.

File details

Details for the file perchancy-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: perchancy-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 17.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for perchancy-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 9217598f7ba7ad36c37fb9c4f63472205e0ecf4e2106de95e7f07facbf0609a2
MD5 d3ddbe5e0bd59df9c2779cc41b454baf
BLAKE2b-256 7ad5eb01ae3aed71404fc42b45913dc02fbdc7e59dbf59e69c99a85db171430e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page