Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -14,134 +14,109 @@ logger = logging.getLogger(__name__)
|
|
14 |
MAX_TEXT_LENGTH = 5000
|
15 |
TEMP_FILES = []
|
16 |
|
17 |
-
# Инициализация клиентов
|
18 |
image_client = None
|
19 |
chat_client = None
|
|
|
20 |
|
21 |
# Стиль интерфейса
|
22 |
theme = gr.themes.Soft()
|
23 |
|
24 |
def initialize_clients(api_key):
|
25 |
-
|
26 |
-
global image_client, chat_client
|
27 |
try:
|
|
|
28 |
image_client = InferenceClient(token=api_key)
|
29 |
chat_client = InferenceClient(provider="together", api_key=api_key)
|
|
|
|
|
|
|
30 |
return True
|
31 |
except Exception as e:
|
32 |
logger.error(f"Initialization error: {str(e)}")
|
33 |
return False
|
34 |
|
35 |
-
|
36 |
-
|
37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
-
#
|
40 |
-
def
|
41 |
-
"""Генерирует изображение с проверкой API ключа"""
|
42 |
if not api_key:
|
43 |
-
return None, "⚠️ Please enter
|
44 |
|
45 |
-
if not
|
46 |
-
return None, "⚠️
|
47 |
|
48 |
try:
|
49 |
-
|
50 |
-
|
51 |
-
model="nerijs/dark-fantasy-illustration-flux",
|
52 |
-
negative_prompt="text, watermark, low quality",
|
53 |
-
guidance_scale=9,
|
54 |
-
height=512,
|
55 |
-
width=512
|
56 |
-
)
|
57 |
|
58 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".
|
59 |
-
tmp_file.
|
60 |
-
|
61 |
-
|
|
|
62 |
|
63 |
except Exception as e:
|
64 |
-
logger.error(f"
|
65 |
-
return None, f"⚠️
|
66 |
|
67 |
-
#
|
68 |
-
async def generate_text(input_text, api_key):
|
69 |
-
"""Генерирует текст с проверкой API ключа"""
|
70 |
-
if not api_key:
|
71 |
-
return None, "⚠️ Please enter your API key first"
|
72 |
-
|
73 |
-
if not initialize_clients(api_key):
|
74 |
-
return None, "⚠️ Invalid API key"
|
75 |
-
|
76 |
-
try:
|
77 |
-
completion = chat_client.chat.completions.create(
|
78 |
-
model="deepseek-ai/DeepSeek-R1",
|
79 |
-
messages=[{"role": "user", "content": input_text}],
|
80 |
-
max_tokens=500
|
81 |
-
)
|
82 |
-
return completion.choices[0].message.content, None
|
83 |
-
except Exception as e:
|
84 |
-
logger.error(f"Text error: {str(e)}")
|
85 |
-
return None, f"⚠️ Error: {str(e)}"
|
86 |
|
87 |
-
# Интерфейс
|
88 |
def create_interface():
|
89 |
-
with gr.Blocks(theme=theme, title="AI Studio") as demo:
|
90 |
-
gr.Markdown("#
|
91 |
|
92 |
-
# Секция
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
)
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
with gr.
|
104 |
-
input_text = gr.Textbox(
|
105 |
-
label="Input Text",
|
106 |
-
placeholder="Enter text with <image>prompt</image> tags...",
|
107 |
-
lines=5
|
108 |
-
)
|
109 |
-
|
110 |
with gr.Row():
|
111 |
-
|
112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
|
|
118 |
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
inputs=[input_text, api_key],
|
123 |
-
outputs=[output_text, status]
|
124 |
-
)
|
125 |
-
|
126 |
-
image_btn.click(
|
127 |
-
lambda text, key: [generate_image(p, key) for p in parse_image_prompts(text)],
|
128 |
-
inputs=[output_text, api_key],
|
129 |
-
outputs=[gallery, status]
|
130 |
-
)
|
131 |
|
132 |
-
|
133 |
|
134 |
# Запуск
|
135 |
if __name__ == "__main__":
|
136 |
try:
|
137 |
demo = create_interface()
|
138 |
-
demo.launch(
|
139 |
-
server_port=7860,
|
140 |
-
show_error=True,
|
141 |
-
share=False
|
142 |
-
)
|
143 |
finally:
|
144 |
-
# Очистка временных файлов
|
145 |
for file in TEMP_FILES:
|
146 |
try:
|
147 |
Path(file).unlink(missing_ok=True)
|
|
|
14 |
MAX_TEXT_LENGTH = 5000
|
15 |
TEMP_FILES = []
|
16 |
|
17 |
+
# Инициализация клиентов
|
18 |
image_client = None
|
19 |
chat_client = None
|
20 |
+
tts_voices = []
|
21 |
|
22 |
# Стиль интерфейса
|
23 |
theme = gr.themes.Soft()
|
24 |
|
25 |
def initialize_clients(api_key):
|
26 |
+
global image_client, chat_client, tts_voices
|
|
|
27 |
try:
|
28 |
+
# Инициализация клиентов API
|
29 |
image_client = InferenceClient(token=api_key)
|
30 |
chat_client = InferenceClient(provider="together", api_key=api_key)
|
31 |
+
|
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():
|
40 |
+
global tts_voices
|
41 |
+
voices = await edge_tts.list_voices()
|
42 |
+
tts_voices = [f"{v['ShortName']} ({v['Gender']})" for v in voices]
|
43 |
+
|
44 |
+
# Функция очистки текста
|
45 |
+
def clean_text(text):
|
46 |
+
text = re.sub(r'[*_~><`#%$^]', '', 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)
|
59 |
+
communicate = edge_tts.Communicate(text, voice.split()[0])
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
|
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():
|
86 |
+
# Вкладка TTS
|
87 |
+
with gr.Tab("🔊 Text-to-Speech"):
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
with gr.Row():
|
89 |
+
with gr.Column():
|
90 |
+
tts_text = gr.Textbox(label="Text to speak", lines=5)
|
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 |
|
114 |
# Запуск
|
115 |
if __name__ == "__main__":
|
116 |
try:
|
117 |
demo = create_interface()
|
118 |
+
demo.launch(server_port=7860)
|
|
|
|
|
|
|
|
|
119 |
finally:
|
|
|
120 |
for file in TEMP_FILES:
|
121 |
try:
|
122 |
Path(file).unlink(missing_ok=True)
|