Rooni commited on
Commit
cd00e66
·
verified ·
1 Parent(s): 7995987

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -23
app.py CHANGED
@@ -5,24 +5,23 @@ from deep_translator import GoogleTranslator
5
  from langdetect import detect
6
  from huggingface_hub import InferenceClient
7
  import gradio as gr
 
8
 
9
  def get_random_api_key():
10
  keys = os.getenv("KEYS", "").split(",")
11
- if keys and keys[0]: # Check if KEYS is set and not empty
12
  return random.choice(keys).strip()
13
  else:
14
  raise ValueError("API keys not found. Please set the KEYS environment variable.")
15
 
16
- # Ссылка на файл CSS
17
- css_url = "https://neurixyufi-aihub.static.hf.space/style.css"
18
 
19
- # Получение CSS по ссылке
20
  try:
21
  response = requests.get(css_url)
22
  response.raise_for_status()
23
  css = response.text + " h1{text-align:center} .container { max-width: 800px; margin: 0 auto; }"
24
  except requests.exceptions.RequestException as e:
25
- print(f"Ошибка при загрузке CSS: {e}")
26
  css = " h1{text-align:center} .container { max-width: 800px; margin: 0 auto; }"
27
 
28
 
@@ -33,12 +32,11 @@ def generate_story(prompt, style):
33
  language = detect(prompt)
34
  if language != 'en':
35
  prompt = GoogleTranslator(source=language, target='en').translate(prompt)
36
-
37
  messages = [
38
  {"role": "system", "content": f"Напиши историю в стиле {style}."},
39
  {"role": "user", "content": prompt}
40
  ]
41
-
42
  completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, temperature=0.7, max_tokens=1000)
43
  story = completion.choices[0].message.content
44
  return story
@@ -46,38 +44,38 @@ def generate_story(prompt, style):
46
  return f"Ошибка генерации: {e}"
47
 
48
 
 
49
  def edit_story(original_story, edited_prompt):
50
  try:
51
  client = InferenceClient(api_key=get_random_api_key())
52
-
53
  messages = [
54
  {"role": "system", "content": "Отредактируй историю, учитывая предоставленные указания."},
55
  {"role": "user", "content": edited_prompt},
56
  {"role": "assistant", "content": original_story}
57
  ]
58
-
59
  completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, temperature=0.7, max_tokens=1000)
60
  edited_story = completion.choices[0].message.content
61
  return edited_story
62
  except Exception as e:
63
  return f"Ошибка редактирования: {e}"
64
 
65
- def next_story(original_story, next_prompt=""):
 
66
  try:
67
  client = InferenceClient(api_key=get_random_api_key())
68
-
69
  messages = [
70
  {"role": "system", "content": "Продли историю, учитывая предоставленные указания. Продливай В ТОЧНОСТИ С КОНЦА, прям с того же символа, слова, предложения."},
71
- {"role": "user", "content": edited_prompt},
72
  {"role": "assistant", "content": original_story}
73
  ]
74
-
75
- completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, temperature=0.7, max_tokens=2500)
76
  next_story = completion.choices[0].message.content
77
  return next_story
78
  except Exception as e:
79
  return f"Ошибка продления: {e}"
80
 
 
 
81
  with gr.Blocks(css=css) as demo:
82
  with gr.Row():
83
  style_choices = ["Приключенческая", "Научно-фантастическая", "Романтическая", "Комедийная", "Трагическая", "Введите свой стиль:"]
@@ -86,22 +84,21 @@ with gr.Blocks(css=css) as demo:
86
  prompt = gr.Textbox(label="Введите запрос для истории", placeholder="Например: История о путешествии в космос", lines=5)
87
  with gr.Row():
88
  generate_button = gr.Button("Сгенерировать историю", variant='primary')
89
-
90
  with gr.Row():
91
  output_story = gr.Textbox(label="История", lines=10)
92
-
93
  with gr.Tab("Редактирование"):
94
  edited_prompt = gr.Textbox(label="Введите изменения для истории", placeholder="Например: Сделай историю более захватывающей", lines=5)
95
  edited_story = gr.Textbox(label="Отредактированная история", lines=10)
96
  edit_button = gr.Button("Отредактировать", variant='primary')
97
-
98
  with gr.Tab("Продление"):
99
- next_prompt = gr.Textbox(label="Введите изменения для истории", placeholder="Например: Сделай историю более захватывающей", lines=5)
100
  next_story = gr.Textbox(label="Продолжение истории", lines=10)
101
  next_button = gr.Button("Продлить", variant='primary')
102
-
103
- generate_button.click(generate_story, inputs=[prompt, style], outputs=[output_story], concurrency_limit=250)
104
- edit_button.click(edit_story, inputs=[output_story, edited_prompt], outputs=[edited_story], concurrency_limit=250)
105
- next_button.click(next_story, inputs=[output_story, next_prompt], outputs=[next_story], concurrency_limit=250)
106
 
107
- demo.launch(show_api=False, share=False)
 
 
 
 
 
5
  from langdetect import detect
6
  from huggingface_hub import InferenceClient
7
  import gradio as gr
8
+ import inspect
9
 
10
  def get_random_api_key():
11
  keys = os.getenv("KEYS", "").split(",")
12
+ if keys and keys[0]:
13
  return random.choice(keys).strip()
14
  else:
15
  raise ValueError("API keys not found. Please set the KEYS environment variable.")
16
 
 
 
17
 
18
+ css_url = "https://neurixyufi-aihub.static.hf.space/style.css"
19
  try:
20
  response = requests.get(css_url)
21
  response.raise_for_status()
22
  css = response.text + " h1{text-align:center} .container { max-width: 800px; margin: 0 auto; }"
23
  except requests.exceptions.RequestException as e:
24
+ print(f"Ошибка загрузки CSS: {e}")
25
  css = " h1{text-align:center} .container { max-width: 800px; margin: 0 auto; }"
26
 
27
 
 
32
  language = detect(prompt)
33
  if language != 'en':
34
  prompt = GoogleTranslator(source=language, target='en').translate(prompt)
35
+
36
  messages = [
37
  {"role": "system", "content": f"Напиши историю в стиле {style}."},
38
  {"role": "user", "content": prompt}
39
  ]
 
40
  completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, temperature=0.7, max_tokens=1000)
41
  story = completion.choices[0].message.content
42
  return story
 
44
  return f"Ошибка генерации: {e}"
45
 
46
 
47
+
48
  def edit_story(original_story, edited_prompt):
49
  try:
50
  client = InferenceClient(api_key=get_random_api_key())
 
51
  messages = [
52
  {"role": "system", "content": "Отредактируй историю, учитывая предоставленные указания."},
53
  {"role": "user", "content": edited_prompt},
54
  {"role": "assistant", "content": original_story}
55
  ]
 
56
  completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, temperature=0.7, max_tokens=1000)
57
  edited_story = completion.choices[0].message.content
58
  return edited_story
59
  except Exception as e:
60
  return f"Ошибка редактирования: {e}"
61
 
62
+
63
+ def next_story(original_story, next_prompt):
64
  try:
65
  client = InferenceClient(api_key=get_random_api_key())
 
66
  messages = [
67
  {"role": "system", "content": "Продли историю, учитывая предоставленные указания. Продливай В ТОЧНОСТИ С КОНЦА, прям с того же символа, слова, предложения."},
68
+ {"role": "user", "content": next_prompt},
69
  {"role": "assistant", "content": original_story}
70
  ]
71
+ completion = client.chat.completions.create(model="Qwen/Qwen2.5-Coder-32B-Instruct", messages=messages, temperature=0.7, max_tokens=1000)
 
72
  next_story = completion.choices[0].message.content
73
  return next_story
74
  except Exception as e:
75
  return f"Ошибка продления: {e}"
76
 
77
+
78
+
79
  with gr.Blocks(css=css) as demo:
80
  with gr.Row():
81
  style_choices = ["Приключенческая", "Научно-фантастическая", "Романтическая", "Комедийная", "Трагическая", "Введите свой стиль:"]
 
84
  prompt = gr.Textbox(label="Введите запрос для истории", placeholder="Например: История о путешествии в космос", lines=5)
85
  with gr.Row():
86
  generate_button = gr.Button("Сгенерировать историю", variant='primary')
 
87
  with gr.Row():
88
  output_story = gr.Textbox(label="История", lines=10)
89
+
90
  with gr.Tab("Редактирование"):
91
  edited_prompt = gr.Textbox(label="Введите изменения для истории", placeholder="Например: Сделай историю более захватывающей", lines=5)
92
  edited_story = gr.Textbox(label="Отредактированная история", lines=10)
93
  edit_button = gr.Button("Отредактировать", variant='primary')
94
+
95
  with gr.Tab("Продление"):
96
+ next_prompt = gr.Textbox(label="Введите изменения для продления истории", placeholder="Например: Продолжи историю", lines=5)
97
  next_story = gr.Textbox(label="Продолжение истории", lines=10)
98
  next_button = gr.Button("Продлить", variant='primary')
 
 
 
 
99
 
100
+ generate_button.click(generate_story, inputs=[prompt, style], outputs=[output_story], queue=False, api_name="generate_story", concurrency_limit=250)
101
+ edit_button.click(edit_story, inputs=[output_story, edited_prompt], outputs=[edited_story], queue=False, api_name="edit_story", concurrency_limit=250)
102
+ next_button.click(next_story, inputs=[output_story, next_prompt], outputs=[next_story], queue=False, api_name="next_story", concurrency_limit=250)
103
+
104
+ demo.launch(show_api=False, share=False)