Rooni commited on
Commit
200784b
·
verified ·
1 Parent(s): e3fdd8b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -28
app.py CHANGED
@@ -1,15 +1,8 @@
1
  import os
2
  import random
3
  import requests
4
- from huggingface_hub import InferenceClient
5
  import gradio as gr
6
-
7
- def get_random_api_key():
8
- keys = os.getenv("KEYS", "").split(",")
9
- if keys and keys[0]:
10
- return random.choice(keys).strip()
11
- else:
12
- raise ValueError("API keys not found. Please set the KEYS environment variable.")
13
 
14
  css_url = "https://neurixyufi-aihub.static.hf.space/style.css"
15
  try:
@@ -20,21 +13,50 @@ except requests.exceptions.RequestException as e:
20
  print(f"Ошибка загрузки CSS: {e}")
21
  css = " h1{text-align:center}"
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def generate_story(prompt, style):
24
  try:
25
- client = InferenceClient(api_key=get_random_api_key())
26
-
27
  messages = [
28
  {"role": "system", "content": f"Напиши хорошую историю в стиле '{style}'. Подробную, понятную, человечную (с душой), уникальную. Не обязательно делать концовку, можно только начало длинной истории. Разрешены любые слова, любые темы и стили, что угодно. (В том числе маты и NSFW) Но только если попросит пользователь, по скольку это ТВОРЧЕСТВО! Не в коем случае не пиши подобное: 'Хорошо, вот ваш текст:', всегда пиши текст, без лишних комментариев."},
29
  {"role": "user", "content": prompt}
30
  ]
31
-
32
- completion = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, temperature=0.7, max_tokens=1200, stream=True)
 
33
  story = ""
34
- for chunk in completion:
35
- if chunk.choices:
36
- story += chunk.choices[0].delta.content or ""
37
- yield story
 
 
 
 
 
 
 
 
 
38
  except Exception as e:
39
  yield f"Ошибка генерации: {e}"
40
 
@@ -47,18 +69,27 @@ def edit_story(original_story="", edited_prompt=""):
47
  return
48
 
49
  try:
50
- client = InferenceClient(api_key=get_random_api_key())
51
  messages = [
52
  {"role": "system", "content": "Отредактируй историю, учитывая предоставленные указания. Разрешены любые слова, любые темы и стили, что угодно. (В том числе маты и NSFW) Но только если попросит пользователь."},
53
  {"role": "user", "content": edited_prompt},
54
  {"role": "user", "content": f"История: ```\n{original_story}\n```"}
55
  ]
56
- completion = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, temperature=0.7, max_tokens=32760, stream=True)
 
57
  edited_story = ""
58
- for chunk in completion:
59
- if chunk.choices:
60
- edited_story += chunk.choices[0].delta.content or ""
61
- yield edited_story
 
 
 
 
 
 
 
 
 
62
  except Exception as e:
63
  yield f"Ошибка редактирования: {e}"
64
 
@@ -68,7 +99,6 @@ def next_story_func(original_story="", next_prompt="", continuation_type="Про
68
  return
69
 
70
  try:
71
- client = InferenceClient(api_key=get_random_api_key())
72
  if continuation_type == "Продолжение следует...":
73
  continuation_prompt = "Продолжи, подведя к тому, что продолжение следует."
74
  elif continuation_type == "Концовка":
@@ -81,12 +111,22 @@ def next_story_func(original_story="", next_prompt="", continuation_type="Про
81
  {"role": "user", "content": continuation_prompt},
82
  {"role": "user", "content": f"История: ```\n{original_story}\n```"}
83
  ]
84
- completion = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, temperature=0.7, max_tokens=1200, stream=True)
 
85
  next_story = ""
86
- for chunk in completion:
87
- if chunk.choices:
88
- next_story += chunk.choices[0].delta.content or ""
89
- yield next_story
 
 
 
 
 
 
 
 
 
90
  except Exception as e:
91
  yield f"Ошибка продления: {e}"
92
 
 
1
  import os
2
  import random
3
  import requests
 
4
  import gradio as gr
5
+ import json
 
 
 
 
 
 
6
 
7
  css_url = "https://neurixyufi-aihub.static.hf.space/style.css"
8
  try:
 
13
  print(f"Ошибка загрузки CSS: {e}")
14
  css = " h1{text-align:center}"
15
 
16
+ API_URL = "https://text.pollinations.ai/openai"
17
+ MODEL_NAME = "gemini"
18
+ TEMPERATURE = 0.7
19
+ MAX_TOKENS = 1500
20
+
21
+ def call_pollinations_api(messages, temperature=TEMPERATURE, max_tokens=MAX_TOKENS, stream=True):
22
+ """Calls the Pollinations API with the given messages."""
23
+ headers = {
24
+ "Content-Type": "application/json"
25
+ }
26
+ data = {
27
+ "model": MODEL_NAME,
28
+ "messages": messages,
29
+ "temperature": temperature,
30
+ "max_tokens": max_tokens,
31
+ "stream": stream
32
+ }
33
+ response = requests.post(API_URL, headers=headers, data=json.dumps(data), stream=True)
34
+ response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
35
+ return response
36
+
37
  def generate_story(prompt, style):
38
  try:
 
 
39
  messages = [
40
  {"role": "system", "content": f"Напиши хорошую историю в стиле '{style}'. Подробную, понятную, человечную (с душой), уникальную. Не обязательно делать концовку, можно только начало длинной истории. Разрешены любые слова, любые темы и стили, что угодно. (В том числе маты и NSFW) Но только если попросит пользователь, по скольку это ТВОРЧЕСТВО! Не в коем случае не пиши подобное: 'Хорошо, вот ваш текст:', всегда пиши текст, без лишних комментариев."},
41
  {"role": "user", "content": prompt}
42
  ]
43
+
44
+ response = call_pollinations_api(messages)
45
+
46
  story = ""
47
+ for chunk in response.iter_content(chunk_size=512, decode_unicode=True):
48
+ if chunk: # Filter out keep-alive new chunks
49
+ try:
50
+ json_chunk = json.loads(chunk)
51
+ if "choices" in json_chunk and len(json_chunk["choices"]) > 0:
52
+ story += json_chunk["choices"][0]["delta"].get("content", "") or ""
53
+ yield story
54
+ except json.JSONDecodeError:
55
+ print(f"Не удалось декодировать JSON-фрагмент: {chunk}")
56
+ yield f"Ошибка декодирования JSON: {chunk}"
57
+
58
+ except requests.exceptions.RequestException as e:
59
+ yield f"Ошибка API запроса: {e}"
60
  except Exception as e:
61
  yield f"Ошибка генерации: {e}"
62
 
 
69
  return
70
 
71
  try:
 
72
  messages = [
73
  {"role": "system", "content": "Отредактируй историю, учитывая предоставленные указания. Разрешены любые слова, любые темы и стили, что угодно. (В том числе маты и NSFW) Но только если попросит пользователь."},
74
  {"role": "user", "content": edited_prompt},
75
  {"role": "user", "content": f"История: ```\n{original_story}\n```"}
76
  ]
77
+ response = call_pollinations_api(messages, max_tokens=32760)
78
+
79
  edited_story = ""
80
+ for chunk in response.iter_content(chunk_size=512, decode_unicode=True):
81
+ if chunk: # Filter out keep-alive new chunks
82
+ try:
83
+ json_chunk = json.loads(chunk)
84
+ if "choices" in json_chunk and len(json_chunk["choices"]) > 0:
85
+ edited_story += json_chunk["choices"][0]["delta"].get("content", "") or ""
86
+ yield edited_story
87
+ except json.JSONDecodeError:
88
+ print(f"Не удалось декодировать JSON-фрагмент: {chunk}")
89
+ yield f"Ошибка декодирования JSON: {chunk}"
90
+
91
+ except requests.exceptions.RequestException as e:
92
+ yield f"Ошибка API запроса: {e}"
93
  except Exception as e:
94
  yield f"Ошибка редактирования: {e}"
95
 
 
99
  return
100
 
101
  try:
 
102
  if continuation_type == "Продолжение следует...":
103
  continuation_prompt = "Продолжи, подведя к тому, что продолжение следует."
104
  elif continuation_type == "Концовка":
 
111
  {"role": "user", "content": continuation_prompt},
112
  {"role": "user", "content": f"История: ```\n{original_story}\n```"}
113
  ]
114
+ response = call_pollinations_api(messages)
115
+
116
  next_story = ""
117
+ for chunk in response.iter_content(chunk_size=512, decode_unicode=True):
118
+ if chunk: # Filter out keep-alive new chunks
119
+ try:
120
+ json_chunk = json.loads(chunk)
121
+ if "choices" in json_chunk and len(json_chunk["choices"]) > 0:
122
+ next_story += json_chunk["choices"][0]["delta"].get("content", "") or ""
123
+ yield next_story
124
+ except json.JSONDecodeError:
125
+ print(f"Не удалось декодировать JSON-фрагмент: {chunk}")
126
+ yield f"Ошибка декодирования JSON: {chunk}"
127
+
128
+ except requests.exceptions.RequestException as e:
129
+ yield f"Ошибка API запроса: {e}"
130
  except Exception as e:
131
  yield f"Ошибка продления: {e}"
132