KevinSmith94624 commited on
Commit
5f057b5
Β·
verified Β·
1 Parent(s): 4ee9262

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +261 -63
app.py CHANGED
@@ -1,64 +1,262 @@
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers import TextToVideoSDPipeline, DiffusionPipeline
3
+ from diffusers.utils import export_to_video
4
  import gradio as gr
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM
6
+ import PIL
7
+ from io import BytesIO
8
+ from gtts import gTTS
9
+ import time
10
+ from pydub import AudioSegment
11
+ import nltk
12
+ from together import Together
13
+ import base64
14
+
15
+ tokenizer = AutoTokenizer.from_pretrained("ParisNeo/LLama-3.2-3B-Lollms-Finetuned-GGUF")
16
+ model0 = AutoModelForCausalLM.from_pretrained("ParisNeo/LLama-3.2-3B-Lollms-Finetuned-GGUF", ignore_mismatched_sizes=True)
17
+
18
+ device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")
19
+ model0 = model0.to(device)
20
+
21
+ # Initialize Chat History
22
+ def chat_with_llama(user_input, chat_history):
23
+ # Prepare formatted prompt
24
+ prompt = "You are a helpful, respectful and honest general-purpose assistant."
25
+ for user_content, assist_content in chat_history:
26
+ prompt += f"user: {user_content}\n"
27
+ prompt += f"assistant: {assist_content}\n"
28
+ prompt += f"user: {user_input}\n'assistant:"
29
+
30
+ # Tokenize and generate response
31
+ inputs = tokenizer(prompt, return_tensors="pt").to("cuda:1")
32
+ output = model0.generate(inputs["input_ids"], max_length=4096, max_new_tokens = 1024, temperature=0.7, max_time = 10.0, repetition_penalty = 1.0)
33
+ response = tokenizer.decode(output[0], skip_special_tokens=True)
34
+
35
+ # Extract and append assistant's response
36
+ assistant_reply = response.split("assistant:")[-1].split('user:')[0].strip()
37
+ chat_history.append((user_input, assistant_reply))
38
+
39
+ return assistant_reply, chat_history
40
+
41
+ api_key='YOUR API KEY HERE'
42
+ client = Together(api_key=api_key)
43
+
44
+ def chat_api(user_input, chat_history):
45
+ messages = []
46
+ for user_content, assist_content in chat_history:
47
+ messages += [
48
+ {"role":"user", "content":user_content},
49
+ {"role":"assistant", "content":assist_content}
50
+ ]
51
+ messages += [{"role":"user", "content":user_input}]
52
+
53
+ response = client.chat.completions.create(
54
+ model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
55
+ messages=messages,
56
+ )
57
+ reply = response.choices[0].message.content
58
+ chat_history.append((user_input, reply))
59
+ return reply, chat_history
60
+
61
+ def tti_api(prompt, num_steps = 25, width = 512, heights = 512):
62
+ response = client.images.generate(
63
+ prompt=prompt,
64
+ model="black-forest-labs/FLUX.1-dev",
65
+ width=width,
66
+ height=heights,
67
+ steps=num_steps,
68
+ n=1,
69
+ response_format="b64_json"
70
+ )
71
+
72
+ image_data = base64.b64decode(response.data[0].b64_json)
73
+ return image_data
74
+
75
+ prompt = 'A nice black lexus 570 car running on the snowy road.'
76
+ image = tti_api(prompt, num_steps = 25)
77
+ image = PIL.Image.open(BytesIO(image))
78
+ image.save('result.png')
79
+ image.show()
80
+
81
+ def ttv(prompt, num_steps = 50):
82
+ # Load the text-to-video model from Hugging Face
83
+ model_id = "damo-vilab/text-to-video-ms-1.7b" # ModelScope Text-to-Video model
84
+ #model_id = "guoyww/animatediff-motion-adapter-v1-5-2" # ModelScope Text-to-Video
85
+
86
+ pipe = TextToVideoSDPipeline.from_pretrained(model_id, torch_dtype=torch.float16, variant="fp16")
87
+ pipe.to("cuda:0") # Use GPU if available
88
+
89
+ # Generate video frames
90
+ print("Generating video... This may take some time.")
91
+ with torch.no_grad():
92
+ video_frames = pipe(prompt, num_frames=32, height=256, width=256, num_inference_steps=num_steps).frames[0]
93
+ # Save the generated video
94
+ video_path = export_to_video(video_frames, output_video_path="output_video.mp4")
95
+ return video_path
96
+ test_video = ttv('An awesome lexus 570 car running on the snowy road, high quality', num_steps = 50)
97
+
98
+ # Ensure the sentence tokenizer is downloaded (if not already)
99
+ nltk.download('punkt')
100
+
101
+ # Function to convert text to speech and generate SRT content
102
+ def tts(text):
103
+ # Initialize the Google TTS engine with language (e.g., 'en' for English)
104
+ tts = gTTS(text=text, lang='en', slow=False)
105
+
106
+ # Save to an audio file
107
+ audio_path = "output.mp3"
108
+ tts.save(audio_path)
109
+
110
+ # Load the audio file with pydub to get the duration
111
+ audio = AudioSegment.from_mp3(audio_path)
112
+ duration_ms = len(audio) # Duration in milliseconds
113
+
114
+ # Split the text into sentences using NLTK
115
+ sentences = nltk.sent_tokenize(text)
116
+
117
+ # Estimate the duration per sentence
118
+ chunk_duration_ms = duration_ms // len(sentences) # Estimated duration per sentence
119
+
120
+ # Generate SRT content
121
+ srt_content = ""
122
+ start_time = 0 # Start time of the first subtitle
123
+ for idx, sentence in enumerate(sentences):
124
+ end_time = start_time + chunk_duration_ms
125
+ start_time_formatted = time.strftime('%H:%M:%S', time.gmtime(start_time / 1000)) + ',' + f'{start_time % 1000:03d}'
126
+ end_time_formatted = time.strftime('%H:%M:%S', time.gmtime(end_time / 1000)) + ',' + f'{end_time % 1000:03d}'
127
+
128
+ srt_content += f"{idx + 1}\n"
129
+ srt_content += f"{start_time_formatted} --> {end_time_formatted}\n"
130
+ srt_content += f"{sentence}\n\n"
131
+
132
+ start_time = end_time # Update start time for the next sentence
133
+
134
+ return audio_path, srt_content
135
+
136
+ def tti(prompt, num_steps = 50, width = 512, heights = 512):
137
+ # Load the pre-trained Stable Diffusion pipeline from Hugging Face
138
+ pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1")
139
+ #pipe.load_lora_weights("FradigmaDangerYT/dalle-e-mini")
140
+
141
+ # Move the pipeline to GPU (you can select the GPU with cuda:1 for the second GPU)
142
+ device0 = torch.device("cuda:0") # Use "cuda:0" for the first GPU, "cuda:1" for the second GPU
143
+ pipe.to(device0)
144
+ print(heights)
145
+ # Generate an image
146
+ image = pipe(prompt, num_inference_steps = num_steps, width = width, height = heights).images[0] # Generate image from the prompt
147
+ return image
148
+
149
+ prompt = 'A nice black lexus 570 car running on the snowy road.'
150
+ image = tti(prompt, num_steps = 25, width = 320, heights = 240)
151
+ # image = PIL.Image.open(BytesIO(image))
152
+ image.save('result.png')
153
+ image.show()
154
+
155
+
156
+ # If demo is on, turn off demo
157
+ try:
158
+ demo.close()
159
+ except:
160
+ pass
161
+
162
+ with gr.Blocks() as demo:
163
+ gr.Markdown("""
164
+ # Gradio based Text-to-Any Project
165
+ """)
166
+ with gr.Tab(label="Llama-Chat"):
167
+ radios0 = gr.Radio(['use api', 'use loaded model'], value="use api", show_label = False)
168
+ gptDialog = gr.Chatbot(label = "Llama-Chat", max_height=512, min_height=512,
169
+ autoscroll= True)
170
+ with gr.Row(equal_height=True):
171
+ prompt0 = gr.Textbox(label = 'Prompt Input', lines = 1, scale = 9, max_lines=2,
172
+ autofocus=True, autoscroll=True, placeholder='Type your message here...')
173
+ with gr.Column(scale = 1):
174
+ generate_btn0 = gr.Button('generate')
175
+ clear_btn0 = gr.Button('clear')
176
+
177
+ with gr.Tab(label="Text-to-Image/Video"):
178
+ with gr.Row():
179
+ radios1 = gr.Radio(['use api', 'use loaded model'], value="use api", show_label = False)
180
+ steps = gr.Slider(value = 50, minimum = 20, maximum = 100, step = 1, label = 'num_steps')
181
+ width = gr.Slider(value = 1024, minimum = 240, maximum = 1792, step = 16, label = 'width')
182
+ heights = gr.Slider(value = 512, minimum = 160, maximum = 1792, step = 16, label = 'heights')
183
+
184
+ with gr.Row():
185
+ outputImg = gr.Image(type='pil',height= 512, width=512, label="Output Image", interactive=False)
186
+ outputVideo = gr.Video(width=512, height=512, label = "Output Video", interactive=False)
187
+ with gr.Row(equal_height=True):
188
+ prompt1 = gr.Textbox(label = 'Prompt Input', lines = 1, scale = 9, max_lines=2,
189
+ autofocus=True, autoscroll=True, placeholder='Type your message here...')
190
+ with gr.Column(scale = 1):
191
+ generate_btn1 = gr.Button('generate image')
192
+ generate_btn11 = gr.Button('generate video')
193
+
194
+ with gr.Tab(label = "Text-to-Speech"):
195
+ outputAudio = gr.Audio(label="Audio Output", interactive = False)
196
+ outputSrt = gr.Textbox(label = 'Script Output', lines = 10, max_lines = 5, placeholder = 'Script output here')
197
+ with gr.Row(equal_height=False):
198
+ prompt2 = gr.Textbox(label = 'Prompt Input', lines = 5, scale = 9, max_lines=5,
199
+ autofocus=True, autoscroll=True, placeholder='Type your message here...')
200
+ with gr.Column(scale = 1):
201
+ generate_btn2 = gr.Button('generate')
202
+ clear_btn2 = gr.Button('clear')
203
+
204
+ with gr.Tab(label = 'About'):
205
+ pass
206
+
207
+ def generate_txt(prompt, check, history):
208
+ if check == 'use api':
209
+ response, history = chat_api(prompt, history)
210
+ if response == None:
211
+ gr.Warning('Can not reach api.')
212
+ else:
213
+ response, history = chat_with_llama(prompt, history)
214
+ if response == None:
215
+ gr.Warning('Failed to load model.')
216
+ return '', history
217
+
218
+ def clear_chat():
219
+ history = []
220
+ gr.Info('Cleaned successfully!')
221
+ return history
222
+
223
+ def generate_img(prompt, check, num_steps, width, heights):
224
+ if check == 'use api':
225
+ image = tti_api(prompt, num_steps = num_steps, width = width, heights = heights)
226
+ image = PIL.Image.open(BytesIO(image))
227
+ if not image:
228
+ gr.Warning('Can not reach api')
229
+ gr.Info('Generated Image Successfully!')
230
+ else:
231
+ image = tti(prompt, num_steps = num_steps, width = width, heights = heights)
232
+ gr.Info('Generated Image Successfully!')
233
+ return image
234
+
235
+ def generate_video(prompt, num_steps):
236
+ video = ttv(prompt, num_steps)
237
+ gr.Info('Generated Video Successfully!')
238
+ return video
239
+
240
+ def generate_speech(prompt):
241
+ audio, script = tts(prompt)
242
+ gr.Info('Generated Speech Successfully!')
243
+ return audio, script
244
+
245
+ def clear_speech():
246
+ gr.Info('Cleaned Successfully!')
247
+ return None, ''
248
+
249
+ prompt0.submit(generate_txt, [prompt0, radios0, gptDialog], [prompt0, gptDialog])
250
+ prompt1.submit(generate_img, [prompt1, radios1], [outputImg])
251
+
252
+ # generate button click event
253
+ generate_btn0.click(generate_txt, [prompt0, radios0, gptDialog], [prompt0, gptDialog])
254
+ generate_btn1.click(generate_img, [prompt1, radios1, steps, width, heights], [outputImg])
255
+ generate_btn11.click(generate_video, [prompt1, steps], [outputVideo])
256
+ generate_btn2.click(generate_speech, [prompt2], [outputAudio, outputSrt])
257
+
258
+ # clear button click event
259
+ clear_btn0.click(clear_chat, [], [gptDialog])
260
+ clear_btn2.click(clear_speech, [], [outputAudio, outputSrt])
261
+ demo.launch(share = True)
262
+