Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -14,23 +14,37 @@ logger = logging.getLogger(__name__)
|
|
14 |
MAX_TEXT_LENGTH = 5000
|
15 |
TEMP_FILES = []
|
16 |
|
17 |
-
# Инициализация клиентов
|
18 |
-
|
19 |
-
|
20 |
-
raise ValueError("HF_API_KEY not found in environment variables")
|
21 |
-
|
22 |
-
image_client = InferenceClient(token=HF_API_KEY)
|
23 |
-
chat_client = InferenceClient(provider="together", api_key=HF_API_KEY)
|
24 |
|
25 |
# Стиль интерфейса
|
26 |
theme = gr.themes.Soft()
|
27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
# Парсер промптов
|
29 |
def parse_image_prompts(text):
|
30 |
return re.findall(r'<image>(.*?)<\/image>', text, re.DOTALL)
|
31 |
|
32 |
# Генератор изображений
|
33 |
-
def generate_image(prompt):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
try:
|
35 |
response = image_client.text_to_image(
|
36 |
prompt.strip(),
|
@@ -51,7 +65,14 @@ def generate_image(prompt):
|
|
51 |
return None, f"⚠️ Error: {str(e)}"
|
52 |
|
53 |
# Генератор текста
|
54 |
-
async def generate_text(input_text):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
try:
|
56 |
completion = chat_client.chat.completions.create(
|
57 |
model="deepseek-ai/DeepSeek-R1",
|
@@ -65,13 +86,23 @@ async def generate_text(input_text):
|
|
65 |
|
66 |
# Интерфейс
|
67 |
def create_interface():
|
68 |
-
with gr.Blocks(theme=theme, title="
|
69 |
-
gr.Markdown("#
|
70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
with gr.Row():
|
72 |
with gr.Column():
|
73 |
input_text = gr.Textbox(
|
74 |
-
label="Input",
|
75 |
placeholder="Enter text with <image>prompt</image> tags...",
|
76 |
lines=5
|
77 |
)
|
@@ -81,19 +112,20 @@ def create_interface():
|
|
81 |
image_btn = gr.Button("Generate Images", variant="secondary")
|
82 |
|
83 |
with gr.Column():
|
84 |
-
output_text = gr.Textbox(label="
|
85 |
-
gallery = gr.Gallery(label="Images", columns=2)
|
86 |
status = gr.HTML()
|
87 |
|
|
|
88 |
text_btn.click(
|
89 |
generate_text,
|
90 |
-
inputs=input_text,
|
91 |
outputs=[output_text, status]
|
92 |
)
|
93 |
|
94 |
image_btn.click(
|
95 |
-
lambda
|
96 |
-
inputs=output_text,
|
97 |
outputs=[gallery, status]
|
98 |
)
|
99 |
|
@@ -103,8 +135,13 @@ def create_interface():
|
|
103 |
if __name__ == "__main__":
|
104 |
try:
|
105 |
demo = create_interface()
|
106 |
-
demo.launch(
|
|
|
|
|
|
|
|
|
107 |
finally:
|
|
|
108 |
for file in TEMP_FILES:
|
109 |
try:
|
110 |
Path(file).unlink(missing_ok=True)
|
|
|
14 |
MAX_TEXT_LENGTH = 5000
|
15 |
TEMP_FILES = []
|
16 |
|
17 |
+
# Инициализация клиентов (будет выполнена после получения API ключа)
|
18 |
+
image_client = None
|
19 |
+
chat_client = None
|
|
|
|
|
|
|
|
|
20 |
|
21 |
# Стиль интерфейса
|
22 |
theme = gr.themes.Soft()
|
23 |
|
24 |
+
def initialize_clients(api_key):
|
25 |
+
"""Инициализирует клиенты API с полученным ключом"""
|
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 |
def parse_image_prompts(text):
|
37 |
return re.findall(r'<image>(.*?)<\/image>', text, re.DOTALL)
|
38 |
|
39 |
# Генератор изображений
|
40 |
+
def generate_image(prompt, api_key):
|
41 |
+
"""Генерирует изображение с проверкой API ключа"""
|
42 |
+
if not api_key:
|
43 |
+
return None, "⚠️ Please enter your API key first"
|
44 |
+
|
45 |
+
if not initialize_clients(api_key):
|
46 |
+
return None, "⚠️ Invalid API key"
|
47 |
+
|
48 |
try:
|
49 |
response = image_client.text_to_image(
|
50 |
prompt.strip(),
|
|
|
65 |
return None, f"⚠️ Error: {str(e)}"
|
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",
|
|
|
86 |
|
87 |
# Интерфейс
|
88 |
def create_interface():
|
89 |
+
with gr.Blocks(theme=theme, title="AI Studio") as demo:
|
90 |
+
gr.Markdown("# 🔑 AI Content Generator")
|
91 |
|
92 |
+
# Секция для ввода API ключа
|
93 |
+
with gr.Row():
|
94 |
+
api_key = gr.Textbox(
|
95 |
+
label="HuggingFace API Key",
|
96 |
+
type="password",
|
97 |
+
placeholder="Enter your HF_API_KEY here...",
|
98 |
+
info="Get your key from https://huggingface.co/settings/tokens"
|
99 |
+
)
|
100 |
+
|
101 |
+
# Основная секция
|
102 |
with gr.Row():
|
103 |
with gr.Column():
|
104 |
input_text = gr.Textbox(
|
105 |
+
label="Input Text",
|
106 |
placeholder="Enter text with <image>prompt</image> tags...",
|
107 |
lines=5
|
108 |
)
|
|
|
112 |
image_btn = gr.Button("Generate Images", variant="secondary")
|
113 |
|
114 |
with gr.Column():
|
115 |
+
output_text = gr.Textbox(label="Generated Text", interactive=False)
|
116 |
+
gallery = gr.Gallery(label="Generated Images", columns=2)
|
117 |
status = gr.HTML()
|
118 |
|
119 |
+
# Обработчики событий
|
120 |
text_btn.click(
|
121 |
generate_text,
|
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 |
|
|
|
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)
|