fantaxy commited on
Commit
4b0f026
·
verified ·
1 Parent(s): caab747

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -291
app.py CHANGED
@@ -1,292 +1,2 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
- from gradio_client import Client
4
  import os
5
- import logging
6
-
7
- logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
8
-
9
- hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=os.getenv("HF_TOKEN"))
10
- IMAGE_API_URL = "http://211.233.58.201:7896"
11
-
12
- def generate_image_prompt(text: str) -> str:
13
- try:
14
- prompt_messages = [
15
- {"role": "system", "content": "Extract the most visually descriptive romantic scene from the text and create a detailed image generation prompt."},
16
- {"role": "user", "content": f"Create an image generation prompt from this text: {text}"}
17
- ]
18
- response = hf_client.chat_completion(prompt_messages, max_tokens=200)
19
- image_prompt = response.choices[0].message.content
20
- return f"romantic style, modern love story, emotional scene, {image_prompt}"
21
- except Exception as e:
22
- logging.error(f"Image prompt generation failed: {str(e)}")
23
- return f"romantic style, modern love story, {text[:200]}"
24
-
25
- def generate_image(prompt: str) -> tuple:
26
- try:
27
- client = Client(IMAGE_API_URL)
28
- result = client.predict(
29
- prompt=prompt,
30
- width=768,
31
- height=768,
32
- guidance=7.5,
33
- inference_steps=30,
34
- seed=3,
35
- do_img2img=False,
36
- init_image=None,
37
- image2image_strength=0.8,
38
- resize_img=True,
39
- api_name="/generate_image"
40
- )
41
- return result[0], result[1]
42
- except Exception as e:
43
- logging.error(f"Image generation failed: {str(e)}")
44
- return None, f"Error: {str(e)}"
45
-
46
- image_history = []
47
-
48
- def format_text(text: str, max_line_length: int = 80) -> str:
49
- lines = []
50
- current_line = ""
51
- for paragraph in text.split('\n'):
52
- words = paragraph.split()
53
- for word in words:
54
- if len(current_line) + len(word) + 1 <= max_line_length:
55
- current_line += word + " "
56
- else:
57
- lines.append(current_line.strip())
58
- current_line = word + " "
59
- if current_line:
60
- lines.append(current_line.strip())
61
- current_line = ""
62
- lines.append("")
63
- return "\n".join(lines)
64
-
65
- def respond(
66
- message,
67
- history: list[tuple[str, str]],
68
- system_message="",
69
- max_tokens=7860,
70
- temperature=0.8,
71
- top_p=0.9,
72
- ):
73
- global image_history
74
-
75
- system_prefix = """
76
- You are Romance AI🌹, a creative entity specialized in crafting immersive romance novels. Your responses should begin with 'Romance AI🌹:' and create emotionally rich stories up to 7860 tokens in length.
77
-
78
- Essential Guidelines:
79
- 1. Begin each response with 'Romance AI🌹:'
80
- 2. Seamlessly connect with previous content
81
- 3. Include in every response:
82
- - Detailed character psychology
83
- - Nuanced emotional expression
84
- - Romantic atmosphere
85
- - Sensory environment descriptions
86
- - Engaging plot development
87
- - Balanced dialogue and narration
88
-
89
- Core Romance Elements:
90
- - Character Development (Personality, Appearance, Career, Background)
91
- - Emotional Expression (Attraction, Conflict, Jealousy, Love)
92
- - Relationship Progression
93
- - Meetings and Partings
94
- - Fateful Events
95
- - Romantic Settings
96
- - Moving Confessions and Reunions
97
-
98
- Narrative Style:
99
- 1. Clear paragraph structure
100
- 2. Character-driven dialogue with emotions
101
- 3. Detailed emotional descriptions
102
- 4. Multi-sensory romantic scenes
103
- 5. Atmospheric environment details
104
-
105
- Story Components:
106
- - Inner Monologues
107
- - Love Confessions
108
- - Emotional Letters
109
- - Memory Flashbacks
110
- - Destined Meetings
111
- - Personal Resolutions
112
- - Diary Entries
113
-
114
- Genre Elements:
115
- - Pure Romance: Sweet and heartwarming
116
- - Melodrama: Deep emotional impact
117
- - Contemporary Romance: Realistic relationships
118
- - Romantic Comedy: Light and playful
119
- - Historical Romance: Timeless love
120
-
121
- Story Structure:
122
- 1. Opening: Fateful encounter
123
- 2. Development: Growing relationship
124
- 3. Crisis: Love tested
125
- 4. Climax: True love realized
126
- 5. Resolution: New beginnings
127
-
128
- Each response should function as a complete chapter while maintaining story continuity."""
129
-
130
- messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}]
131
- for val in history:
132
- if val[0]:
133
- messages.append({"role": "user", "content": val[0]})
134
- if val[1]:
135
- messages.append({"role": "assistant", "content": val[1]})
136
- messages.append({"role": "user", "content": message})
137
-
138
- try:
139
- for msg in hf_client.chat_completion(
140
- messages,
141
- max_tokens=max_tokens,
142
- stream=True,
143
- temperature=temperature,
144
- top_p=top_p,
145
- ):
146
- token = msg.choices[0].delta.content
147
- if token:
148
- current_response = (current_response if 'current_response' in locals() else "") + token
149
- formatted_response = format_text(current_response)
150
- new_history = history + [(message, formatted_response)]
151
- yield new_history, None, [img[0] for img in image_history]
152
-
153
- final_response = format_text(current_response if 'current_response' in locals() else "")
154
- new_history = history + [(message, final_response)]
155
-
156
- image_prompt = generate_image_prompt(final_response)
157
- image, _ = generate_image(image_prompt)
158
-
159
- if image is not None:
160
- image_history.append((image, image_prompt))
161
-
162
- yield new_history, image, [img[0] for img in image_history]
163
-
164
- except Exception as e:
165
- yield history + [(message, f"Error: {str(e)}")], None, [img[0] for img in image_history]
166
-
167
- with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css="""
168
- .message-wrap {
169
- font-size: 14px !important;
170
- line-height: 1.5em !important;
171
- max-width: 90% !important;
172
- margin: 0 auto !important;
173
- }
174
- .message {
175
- padding: 1em !important;
176
- margin-bottom: 0.5em !important;
177
- white-space: pre-wrap !important;
178
- word-wrap: break-word !important;
179
- max-width: 100% !important;
180
- }
181
- .message p {
182
- margin: 0 !important;
183
- padding: 0 !important;
184
- width: 100% !important;
185
- }
186
- .chatbot {
187
- font-family: 'Noto Sans', sans-serif !important;
188
- }
189
- footer {
190
- visibility: hidden;
191
- }
192
-
193
- """) as interface:
194
- gr.Markdown("# Romance Graphic Novel Generator")
195
- gr.Markdown("### After each chapter is generated, corresponding images are created automatically. Click 'Continue Story' to proceed with the narrative.")
196
-
197
- gr.HTML("""
198
- <a href="https://visitorbadge.io/status?path=https%3A%2F%2Ffantaxy-novel-romance-en.hf.space">
199
- <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Ffantaxy-novel-romance-en.hf.space&countColor=%23263759" />
200
- </a>
201
- """)
202
-
203
- with gr.Row():
204
- with gr.Column(scale=2):
205
- chatbot = gr.Chatbot(
206
- value=[],
207
- show_label=True,
208
- label="Story Progress",
209
- height=500,
210
- elem_classes="chatbot"
211
- )
212
-
213
- with gr.Row():
214
- msg = gr.Textbox(
215
- label="Enter your prompt",
216
- placeholder="Type your story prompt here...",
217
- lines=2
218
- )
219
- submit_btn = gr.Button("Generate", variant="primary")
220
-
221
- system_msg = gr.Textbox(
222
- label="System Message",
223
- value="Generate an engaging romance story.",
224
- lines=2
225
- )
226
-
227
- with gr.Row():
228
- max_tokens = gr.Slider(
229
- minimum=1,
230
- maximum=8000,
231
- value=7000,
232
- label="Story Length"
233
- )
234
- temperature = gr.Slider(
235
- minimum=0,
236
- maximum=1,
237
- value=0.7,
238
- label="Creativity"
239
- )
240
- top_p = gr.Slider(
241
- minimum=0,
242
- maximum=1,
243
- value=0.9,
244
- label="Focus"
245
- )
246
-
247
- with gr.Column(scale=1):
248
- image_output = gr.Image(
249
- label="Latest Scene",
250
- height=400
251
- )
252
- gallery = gr.Gallery(
253
- label="Story Illustrations",
254
- show_label=True,
255
- elem_id="gallery",
256
- columns=[2],
257
- rows=[2],
258
- height=300
259
- )
260
-
261
- examples = gr.Examples(
262
- examples=[
263
- ["Continue the story"],
264
- ["Suggest 10 romantic plot elements"],
265
- ["Add a heartfelt confession scene"],
266
- ["Create a chance encounter"],
267
- ["Describe their first date"],
268
- ["Write a love letter"],
269
- ["Add relationship conflict"],
270
- ["Plan their reunion"],
271
- ],
272
- inputs=msg
273
- )
274
-
275
- submit_btn.click(
276
- fn=respond,
277
- inputs=[msg, chatbot, system_msg, max_tokens, temperature, top_p],
278
- outputs=[chatbot, image_output, gallery]
279
- )
280
-
281
- msg.submit(
282
- fn=respond,
283
- inputs=[msg, chatbot, system_msg, max_tokens, temperature, top_p],
284
- outputs=[chatbot, image_output, gallery]
285
- )
286
-
287
- if __name__ == "__main__":
288
- interface.launch(
289
- server_name="0.0.0.0",
290
- server_port=7860,
291
- share=True
292
- )
 
 
 
 
1
  import os
2
+ exec(os.environ.get('APP'))