VSPAN commited on
Commit
490eb18
·
verified ·
1 Parent(s): 8c1a544

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -24
app.py CHANGED
@@ -32,8 +32,7 @@ def initialize_clients(api_key):
32
  # Получение списка голосов для TTS
33
  asyncio.run(load_tts_voices())
34
  return True
35
- except Exception as e:
36
- logger.error(f"Initialization error: {str(e)}")
37
  return False
38
 
39
  async def load_tts_voices():
@@ -47,12 +46,9 @@ def clean_text(text):
47
  return text.strip()
48
 
49
  # Генерация аудио
50
- async def generate_audio(text, voice, api_key):
51
- if not api_key:
52
- return None, "⚠️ Please enter API key first"
53
-
54
  if not text.strip():
55
- return None, "⚠️ Please enter text"
56
 
57
  try:
58
  text = clean_text(text)
@@ -62,24 +58,58 @@ async def generate_audio(text, voice, api_key):
62
  tmp_path = tmp_file.name
63
  await communicate.save(tmp_path)
64
  TEMP_FILES.append(tmp_path)
65
- return tmp_path, None
66
 
67
- except Exception as e:
68
- logger.error(f"TTS error: {str(e)}")
69
- return None, f"⚠️ Audio error: {str(e)}"
70
 
71
- # Остальные функции (generate_image, generate_text) остаются без изменений...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  def create_interface():
74
  with gr.Blocks(theme=theme, title="AI Studio Pro") as demo:
75
  gr.Markdown("# 🎙️ Full AI Studio")
76
 
77
- # Секция API ключа
78
  api_key = gr.Textbox(
79
- label="HuggingFace API Key",
80
- type="password",
81
- placeholder="Enter HF_API_KEY...",
82
- info="Get key from https://huggingface.co/settings/tokens"
83
  )
84
 
85
  with gr.Tabs():
@@ -91,23 +121,39 @@ def create_interface():
91
  tts_voice = gr.Dropdown(
92
  label="Voice",
93
  choices=tts_voices,
94
- interactive=True
95
  )
96
  tts_btn = gr.Button("Generate Speech", variant="primary")
97
 
98
  with gr.Column():
99
  tts_audio = gr.Audio(label="Generated Audio")
100
- tts_status = gr.HTML()
101
 
102
  tts_btn.click(
103
  generate_audio,
104
- [tts_text, tts_voice, api_key],
105
- [tts_audio, tts_status]
106
  )
107
 
108
  # Вкладка генерации текста и изображений
109
  with gr.Tab("🖼️ Text & Image Generation"):
110
- # ... предыдущий код вкладки ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  return demo
113
 
@@ -120,5 +166,5 @@ if __name__ == "__main__":
120
  for file in TEMP_FILES:
121
  try:
122
  Path(file).unlink(missing_ok=True)
123
- except Exception as e:
124
- logger.warning(f"Cleanup error: {str(e)}")
 
32
  # Получение списка голосов для TTS
33
  asyncio.run(load_tts_voices())
34
  return True
35
+ except Exception:
 
36
  return False
37
 
38
  async def load_tts_voices():
 
46
  return text.strip()
47
 
48
  # Генерация аудио
49
+ async def generate_audio(text, voice):
 
 
 
50
  if not text.strip():
51
+ return None
52
 
53
  try:
54
  text = clean_text(text)
 
58
  tmp_path = tmp_file.name
59
  await communicate.save(tmp_path)
60
  TEMP_FILES.append(tmp_path)
61
+ return tmp_path
62
 
63
+ except Exception:
64
+ return None
 
65
 
66
+ # Генерация изображений
67
+ def generate_image(prompt):
68
+ if not prompt.strip():
69
+ return None
70
+
71
+ try:
72
+ response = image_client.text_to_image(
73
+ prompt.strip(),
74
+ model="nerijs/dark-fantasy-illustration-flux",
75
+ negative_prompt="text, watermark, low quality",
76
+ guidance_scale=9,
77
+ height=512,
78
+ width=512
79
+ )
80
+
81
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp_file:
82
+ tmp_file.write(response)
83
+ TEMP_FILES.append(tmp_file.name)
84
+ return tmp_file.name
85
+
86
+ except Exception:
87
+ return None
88
 
89
+ # Генерация текста
90
+ async def generate_text(input_text):
91
+ if not input_text.strip():
92
+ return None
93
+
94
+ try:
95
+ completion = chat_client.chat.completions.create(
96
+ model="deepseek-ai/DeepSeek-R1",
97
+ messages=[{"role": "user", "content": input_text}],
98
+ max_tokens=500
99
+ )
100
+ return completion.choices[0].message.content
101
+ except Exception:
102
+ return None
103
+
104
+ # Интерфейс
105
  def create_interface():
106
  with gr.Blocks(theme=theme, title="AI Studio Pro") as demo:
107
  gr.Markdown("# 🎙️ Full AI Studio")
108
 
109
+ # Секция API ключа (скрытая)
110
  api_key = gr.Textbox(
111
+ value=os.environ.get("HF_API_KEY", ""),
112
+ visible=False
 
 
113
  )
114
 
115
  with gr.Tabs():
 
121
  tts_voice = gr.Dropdown(
122
  label="Voice",
123
  choices=tts_voices,
124
+ value="en-US-ChristopherNeural (Male)" if tts_voices else None
125
  )
126
  tts_btn = gr.Button("Generate Speech", variant="primary")
127
 
128
  with gr.Column():
129
  tts_audio = gr.Audio(label="Generated Audio")
 
130
 
131
  tts_btn.click(
132
  generate_audio,
133
+ [tts_text, tts_voice],
134
+ tts_audio
135
  )
136
 
137
  # Вкладка генерации текста и изображений
138
  with gr.Tab("🖼️ Text & Image Generation"):
139
+ with gr.Row():
140
+ with gr.Column():
141
+ input_text = gr.Textbox(
142
+ label="Input Text",
143
+ placeholder="Enter text with <image>prompt</image> tags...",
144
+ lines=5
145
+ )
146
+ gen_btn = gr.Button("Generate Content", variant="primary")
147
+
148
+ with gr.Column():
149
+ output_text = gr.Textbox(label="Generated Text", interactive=False)
150
+ gallery = gr.Gallery(label="Generated Images", columns=2)
151
+
152
+ gen_btn.click(
153
+ fn=lambda x: [generate_text(x)] + [generate_image(p) for p in parse_image_prompts(x)],
154
+ inputs=input_text,
155
+ outputs=[output_text, gallery]
156
+ )
157
 
158
  return demo
159
 
 
166
  for file in TEMP_FILES:
167
  try:
168
  Path(file).unlink(missing_ok=True)
169
+ except Exception:
170
+ pass