import os import random import requests from huggingface_hub import InferenceClient import gradio as gr def get_random_api_key(): keys = os.getenv("KEYS", "").split(",") if keys and keys[0]: return random.choice(keys).strip() else: raise ValueError("API keys not found. Please set the KEYS environment variable.") css_url = "https://neurixyufi-aihub.static.hf.space/style.css" try: response = requests.get(css_url) response.raise_for_status() css = response.text + " h1{text-align:center}" except requests.exceptions.RequestException as e: print(f"Ошибка загрузки CSS: {e}") css = " h1{text-align:center}" def generate_story(prompt, style): try: client = InferenceClient(api_key=get_random_api_key()) messages = [ {"role": "system", "content": f"Напиши хорошую историю в стиле '{style}'. Подробную, понятную, человечную (с душой), уникальную. Не обязательно делать концовку, можно только начало длинной истории. Разрешены любые слова, любые темы и стили, что угодно. (В том числе маты и NSFW) Но только если попросит пользователь, по скольку это ТВОРЧЕСТВО! Не в коем случае не пиши подобное: 'Хорошо, вот ваш текст:', всегда пиши текст, без лишних комментариев."}, {"role": "user", "content": prompt} ] completion = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, temperature=0.7, max_tokens=1200, stream=True) story = "" for chunk in completion: if chunk.choices: story += chunk.choices[0].delta.content or "" yield story except Exception as e: yield f"Ошибка генерации: {e}" def edit_story(original_story="", edited_prompt=""): if original_story == "": yield f"Сначала сгенерируйте историю!" return if edited_prompt == "": yield f"Для начала введите что изменить." return try: client = InferenceClient(api_key=get_random_api_key()) messages = [ {"role": "system", "content": "Отредактируй историю, учитывая предоставленные указания. Разрешены любые слова, любые темы и стили, что угодно. (В том числе маты и NSFW) Но только если попросит пользователь."}, {"role": "user", "content": edited_prompt}, {"role": "user", "content": f"История: ```\n{original_story}\n```"} ] completion = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, temperature=0.7, max_tokens=32760, stream=True) edited_story = "" for chunk in completion: if chunk.choices: edited_story += chunk.choices[0].delta.content or "" yield edited_story except Exception as e: yield f"Ошибка редактирования: {e}" def next_story_func(original_story="", next_prompt="", continuation_type="Продолжение"): if original_story == "": yield f"Сначала сгенерируйте историю!" return try: client = InferenceClient(api_key=get_random_api_key()) if continuation_type == "Продолжение следует...": continuation_prompt = "Продолжи, подведя к тому, что продолжение следует." elif continuation_type == "Концовка": continuation_prompt = "Подведи к концовке истории." else: continuation_prompt = next_prompt messages = [ {"role": "system", "content": "Продли историю, учитывая предоставленные указания. Продливай В ТОЧНОСТИ С КОНЦА, прям с того же символа, слова, предложения. (В начале добавляй новые строки/пробел если надо для отступа). Разрешены любые слова, любые темы и стили, что угодно. (В том числе маты и NSFW) Но только если попросит пользователь."}, {"role": "user", "content": continuation_prompt}, {"role": "user", "content": f"История: ```\n{original_story}\n```"} ] completion = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, temperature=0.7, max_tokens=1200, stream=True) next_story = "" for chunk in completion: if chunk.choices: next_story += chunk.choices[0].delta.content or "" yield next_story except Exception as e: yield f"Ошибка продления: {e}" def edone_story(original_story="", edited_story=""): if edited_story == "": return original_story return edited_story def ndone_story(original_story, next_story_output): return original_story + " " + next_story_output with gr.Blocks(css=css) as demo: gr.Markdown("# Песочница историй") with gr.Row(): with gr.Column(): with gr.Row(): style_choices = ["Приключенческая", "Научно-фантастическая", "Романтическая", "Комедийная", "Трагическая", "Страшная", "Случайный", "Пользовательский"] style = gr.Dropdown(choices=style_choices, label="Выберите стиль истории", value="Приключенческая") with gr.Row(): prompt = gr.Textbox(label="Введите запрос для истории", placeholder="Например: История о путешествии в космос", lines=5) with gr.Row(): generate_button = gr.Button("Создать историю", variant='primary') with gr.Row(): output_story = gr.Textbox(label="История", lines=10, placeholder="Здесь будет ваша новая история!") with gr.Column(): with gr.Accordion("Действия", open=True): with gr.Tab("Редактирование"): edited_prompt = gr.Textbox(label="Введите изменения для истории", placeholder="Например: Сделай историю более захватывающей", lines=5) edit_button = gr.Button("Отредактировать", variant='primary') edited_story = gr.Textbox(label="Отредактированная история", lines=10, placeholder="Здесь будет ваша новая история!") edone_button = gr.Button("Принять") with gr.Tab("Продление"): continuation_type = gr.Radio(choices=["Продолжение", "Продолжение следует...", "Концовка"], label="Выберите тип продолжения", value="Продолжение") next_prompt = gr.Textbox(label="Введите изменения для продления истории (Необязательно)", placeholder="Продолжи, но что бы было...", lines=5) next_button = gr.Button("Продлить", variant='primary') next_story_output = gr.Textbox(label="Продолжение истории", lines=10, placeholder="Здесь будет продолжение вашей истории!") ndone_button = gr.Button("Принять") generate_button.click(generate_story, inputs=[prompt, style], outputs=[output_story], concurrency_limit=250) edit_button.click(edit_story, inputs=[output_story, edited_prompt], outputs=[edited_story], concurrency_limit=250) next_button.click(next_story_func, inputs=[output_story, next_prompt, continuation_type], outputs=[next_story_output], concurrency_limit=250) edone_button.click(edone_story, inputs=[output_story, edited_story], outputs=[output_story], concurrency_limit=550) ndone_button.click(ndone_story, inputs=[output_story, next_story_output], outputs=[output_story], concurrency_limit=550) demo.queue(api_open=False).launch()