Spaces:
Running
Running
File size: 6,648 Bytes
3b46f80 cd00e66 3b46f80 cd00e66 3b46f80 6c03f20 3b46f80 cd00e66 6c03f20 3b46f80 d984f8b 3b46f80 b8ec7a1 3b46f80 3616f86 3b46f80 f643627 3b46f80 5946dcd 3b46f80 b8ec7a1 3b46f80 f643627 3573dca 5946dcd f643627 6c03f20 cd00e66 f643627 cd00e66 7995987 3b46f80 7995987 3b46f80 9b87e69 3b46f80 0f70d2d 8c12ac5 d0ade64 8c12ac5 1fc0d49 8c12ac5 1fc0d49 6c03f20 8c12ac5 1fc0d49 8c12ac5 9b87e69 8c12ac5 1fc0d49 8c12ac5 3b46f80 e0b4568 9b87e69 cd00e66 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
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}'. Подробную, понятную, человечную (с душой), уникальную."},
{"role": "user", "content": prompt}
]
completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, temperature=0.7, max_tokens=1000)
story = completion.choices[0].message.content
return story
except Exception as e:
return f"Ошибка генерации: {e}"
def edit_story(original_story="", edited_prompt=""):
if original_story == "":
return f"Сначала сгенерируйте историю!"
if edited_prompt == "":
return f"Для начала введите что изменить."
try:
client = InferenceClient(api_key=get_random_api_key())
messages = [
{"role": "system", "content": "Отредактируй историю, учитывая предоставленные указания."},
{"role": "user", "content": edited_prompt},
{"role": "assistant", "content": original_story}
]
completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, temperature=0.7, max_tokens=1000)
edited_story = completion.choices[0].message.content
return edited_story
except Exception as e:
return f"Ошибка редактирования: {e}"
def next_story_func(original_story="", next_prompt=""):
if original_story == "":
return f"Сначала сгенерируйте историю!"
try:
client = InferenceClient(api_key=get_random_api_key())
messages = [
{"role": "system", "content": "Продли историю, учитывая предоставленные указания. Продливай В ТОЧНОСТИ С КОНЦА, прям с того же символа, слова, предложения. (В начале добавляй новые строки если надо для отступа)"},
{"role": "user", "content": next_prompt},
{"role": "assistant", "content": original_story}
]
completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, temperature=0.7, max_tokens=1000)
next_story = completion.choices[0].message.content
return next_story
except Exception as e:
return f"Ошибка продления: {e}"
def edone_story(edited_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("Продление"):
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], outputs=[next_story_output], concurrency_limit=250)
edone_button.click(edone_story, inputs=[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.launch(show_api=False, share=False)
|