AiCoderv2 commited on
Commit
b16db00
·
verified ·
1 Parent(s): 86a6f65

Update app.py from anycoder

Browse files
Files changed (1) hide show
  1. app.py +131 -212
app.py CHANGED
@@ -1,217 +1,136 @@
1
  import gradio as gr
2
- import os
3
- import cv2
4
- import numpy as np
5
- from moviepy.editor import *
6
-
7
- from diffusers import StableDiffusionInstructPix2PixPipeline
8
- import torch
9
- from PIL import Image, ImageOps
10
- import time
11
- import psutil
12
- import math
13
  import random
14
-
15
- # Initialize the pipeline
16
- pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix", torch_dtype=torch.float16, safety_checker=None)
17
-
18
- device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶"
19
-
20
- if torch.cuda.is_available():
21
- pipe = pipe.to("cuda")
22
-
23
- def pix2pix(
24
- input_image: Image.Image,
25
- instruction: str,
26
- steps: int,
27
- seed: int,
28
- text_cfg_scale: float,
29
- image_cfg_scale: float,
30
- ):
31
-
32
- width, height = input_image.size
33
- factor = 512 / max(width, height)
34
- factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
35
- width = int((width * factor) // 64) * 64
36
- height = int((height * factor) // 64) * 64
37
- input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
38
-
39
- if instruction == "":
40
- return [input_image, seed]
41
-
42
- generator = torch.manual_seed(seed)
43
- edited_image = pipe(
44
- instruction, image=input_image,
45
- guidance_scale=text_cfg_scale, image_guidance_scale=image_cfg_scale,
46
- num_inference_steps=steps, generator=generator,
47
- ).images[0]
48
- print(f"EDITED: {edited_image}")
49
- return edited_image
50
-
51
- def get_frames(video_in):
52
- frames = []
53
- #resize the video
54
- clip = VideoFileClip(video_in)
55
-
56
- #check fps
57
- if clip.fps > 30:
58
- print("vide rate is over 30, resetting to 30")
59
- clip_resized = clip.resize(height=512)
60
- clip_resized.write_videofile("video_resized.mp4", fps=30)
61
- else:
62
- print("video rate is OK")
63
- clip_resized = clip.resize(height=512)
64
- clip_resized.write_videofile("video_resized.mp4", fps=clip.fps)
65
-
66
- print("video resized to 512 height")
67
-
68
- # Opens the Video file with CV2
69
- cap= cv2.VideoCapture("video_resized.mp4")
70
-
71
- fps = cap.get(cv2.CAP_PROP_FPS)
72
- print("video fps: " + str(fps))
73
- i=0
74
- while(cap.isOpened()):
75
- ret, frame = cap.read()
76
- if ret == False:
77
- break
78
- cv2.imwrite('kang'+str(i)+'.jpg',frame)
79
- frames.append('kang'+str(i)+'.jpg')
80
- i+=1
81
-
82
- cap.release()
83
- cv2.destroyAllWindows()
84
- print("broke the video into frames")
85
-
86
- return frames, fps
87
-
88
- def create_video(frames, fps):
89
- print("building video result")
90
- clip = ImageSequenceClip(frames, fps=fps)
91
- clip.write_videofile("movie.mp4", fps=fps)
92
-
93
- return 'movie.mp4'
94
-
95
- def infer(prompt,video_in, seed_in, trim_value):
96
- print(prompt)
97
- break_vid = get_frames(video_in)
98
-
99
- frames_list= break_vid[0]
100
- fps = break_vid[1]
101
- n_frame = int(trim_value*fps)
102
-
103
- if n_frame >= len(frames_list):
104
- print("video is shorter than the cut value")
105
- n_frame = len(frames_list)
106
-
107
- result_frames = []
108
- print("set stop frames to: " + str(n_frame))
109
-
110
- for i in frames_list[0:int(n_frame)]:
111
- pil_i = Image.open(i).convert("RGB")
112
-
113
- pix2pix_img = pix2pix(pil_i, prompt, 50, seed_in, 7.5, 1.5)
114
- #print(pix2pix_img)
115
- #image = Image.open(pix2pix_img)
116
- #rgb_im = image.convert("RGB")
117
-
118
- # exporting the image
119
- pix2pix_img.save(f"result_img-{i}.jpg")
120
- result_frames.append(f"result_img-{i}.jpg")
121
- print("frame " + i + "/" + str(n_frame) + ": done;")
122
-
123
- final_vid = create_video(result_frames, fps)
124
- print("finished !")
125
-
126
- return final_vid
127
-
128
- title = """
129
- <div style="text-align: center; max-width: 700px; margin: 0 auto;">
130
- <div
131
- style="
132
- display: inline-flex;
133
- align-items: center;
134
- gap: 0.8rem;
135
- font-size: 1.75rem;
136
- "
137
- >
138
- <h1 style="font-weight: 900; margin-bottom: 7px; margin-top: 5px;">
139
- Pix2Pix Video
140
- </h1>
141
- </div>
142
- <p style="margin-bottom: 10px; font-size: 94%">
143
- Apply Instruct Pix2Pix Diffusion to a video
144
- </p>
145
- </div>
146
- """
147
-
148
- article = """
149
-
150
- <div class="footer">
151
- <p>
152
- Examples by <a href="https://twitter.com/CitizenPlain" target="_blank">Nathan Shipley</a> •&nbsp;
153
- Follow <a href="https://twitter.com/fffiloni" target="_blank">Sylvain Filoni</a> for future updates 🤗
154
- </p>
155
- </div>
156
- <div id="may-like-container" style="display: flex;justify-content: center;flex-direction: column;align-items: center;margin-bottom: 30px;">
157
- <p>You may also like: </p>
158
- <div id="may-like-content" style="display:flex;flex-wrap: wrap;align-items:center;height:20px;">
159
-
160
- <svg height="20" width="162" style="margin-left:4px;margin-bottom: 6px;">
161
- <a href="https://huggingface.co/spaces/timbrooks/instruct-pix2pix" target="_blank">
162
- <image href="https://img.shields.io/badge/🤗 Spaces-Instruct_Pix2Pix-blue" src="https://img.shields.io/badge/🤗 Spaces-Instruct_Pix2Pix-blue.png" height="20"/>
163
- </a>
164
- </svg>
165
-
166
- </div>
167
-
168
- </div>
169
-
170
- """
171
-
172
- # Create the Gradio 6 interface
173
  with gr.Blocks() as demo:
174
- with gr.Column(elem_id="col-container"):
175
- gr.HTML(title)
176
- with gr.Row():
177
- with gr.Column():
178
- video_inp = gr.Video(label="Video source", sources=["upload"], elem_id="input-vid")
179
- prompt = gr.Textbox(label="Prompt", placeholder="enter prompt", show_label=False, elem_id="prompt-in")
180
- with gr.Row():
181
- seed_inp = gr.Slider(label="Seed", minimum=0, maximum=2147483647, step=1, value=123456)
182
- trim_in = gr.Slider(label="Cut video at (s)", minimum=1, maximum=5, step=1, value=1)
183
- with gr.Column():
184
- video_out = gr.Video(label="Pix2pix video result", elem_id="video-output")
185
- gr.HTML("""
186
- <a style="display:inline-block" href="https://huggingface.co/spaces/fffiloni/Pix2Pix-Video?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a>
187
- work with longer videos / skip the queue:
188
- """, elem_id="duplicate-container")
189
- submit_btn = gr.Button("Generate Pix2Pix video")
190
-
191
- inputs = [prompt,video_inp,seed_inp, trim_in]
192
- outputs = [video_out]
193
-
194
- ex = gr.Examples(
195
- [
196
- ["Make it a marble sculpture", "./examples/pexels-jill-burrow-7665249_512x512.mp4", 422112651, 4],
197
- ["Make it molten lava", "./examples/Ocean_Pexels_ 8953474_512x512.mp4", 43571876, 4]
198
- ],
199
- inputs=inputs,
200
- )
201
-
202
- gr.HTML(article)
203
-
204
- submit_btn.click(infer, inputs=inputs, outputs=outputs)
205
-
206
- # Launch with Gradio 6 syntax - all parameters in launch()
207
- demo.queue(max_size=12).launch(
208
- theme=gr.themes.Soft(
209
- primary_hue="pink",
210
- secondary_hue="purple",
211
- font=gr.themes.GoogleFont("IBM Plex Sans")
212
- ),
213
- css_paths=["style.css"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  footer_links=[
215
- {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
216
- ]
 
 
 
217
  )
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
2
  import random
3
+ import time
4
+ from datetime import datetime
5
+
6
+ # Simple AI Chatbot Model
7
+ class SimpleChatbot:
8
+ def __init__(self):
9
+ self.responses = {
10
+ "greetings": ["Hello!", "Hi there!", "Greetings!", "Nice to meet you!"],
11
+ "farewells": ["Goodbye!", "See you later!", "Take care!", "Farewell!"],
12
+ "thanks": ["You're welcome!", "No problem!", "Happy to help!", "Anytime!"],
13
+ "questions": ["That's an interesting question!", "Let me think about that...", "I'll get back to you on that!"],
14
+ "default": ["I see.", "Interesting!", "Tell me more.", "Go on...", "I'm listening."]
15
+ }
16
+
17
+ def respond(self, message, history):
18
+ message = message.lower()
19
+
20
+ # Simple intent detection
21
+ if any(word in message for word in ["hi", "hello", "hey", "greetings"]):
22
+ response = random.choice(self.responses["greetings"])
23
+ elif any(word in message for word in ["bye", "goodbye", "farewell", "see you"]):
24
+ response = random.choice(self.responses["farewells"])
25
+ elif any(word in message for word in ["thank", "thanks", "appreciate"]):
26
+ response = random.choice(self.responses["thanks"])
27
+ elif "?" in message:
28
+ response = random.choice(self.responses["questions"])
29
+ else:
30
+ response = random.choice(self.responses["default"])
31
+
32
+ # Add timestamp to response
33
+ timestamp = datetime.now().strftime("%H:%M:%S")
34
+ full_response = f"[{timestamp}] AI: {response}"
35
+
36
+ return full_response
37
+
38
+ # Create chatbot instance
39
+ chatbot = SimpleChatbot()
40
+
41
+ # Custom theme for modern look
42
+ custom_theme = gr.themes.Soft(
43
+ primary_hue="blue",
44
+ secondary_hue="indigo",
45
+ neutral_hue="slate",
46
+ font=gr.themes.GoogleFont("Inter"),
47
+ text_size="lg",
48
+ spacing_size="lg",
49
+ radius_size="md"
50
+ ).set(
51
+ button_primary_background_fill="*primary_600",
52
+ button_primary_background_fill_hover="*primary_700",
53
+ block_title_text_weight="600",
54
+ )
55
+
56
+ # Create Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  with gr.Blocks() as demo:
58
+ gr.Markdown("# 🤖 AI Chatbot")
59
+ gr.Markdown("Built with anycoder - A simple AI chatbot for conversation")
60
+
61
+ with gr.Row():
62
+ with gr.Column(scale=3):
63
+ chatbot_interface = gr.Chatbot(
64
+ label="Chat with AI",
65
+ height=500,
66
+ avatar_images=(
67
+ "https://gradio-builds.s3.amazonaws.com/assets/user-avatar.png",
68
+ "https://gradio-builds.s3.amazonaws.com/assets/bot-avatar.png"
69
+ ),
70
+ show_label=False
71
+ )
72
+ message_input = gr.Textbox(
73
+ label="Your Message",
74
+ placeholder="Type your message here...",
75
+ lines=2,
76
+ show_label=False
77
+ )
78
+
79
+ with gr.Column(scale=1):
80
+ gr.Markdown("## Features")
81
+ gr.Markdown("""
82
+ - ✅ Simple AI responses
83
+ - ✅ Conversation history
84
+ - ✅ Timestamped messages
85
+ - ✅ User-friendly interface
86
+ """)
87
+
88
+ gr.Markdown("## How to Use")
89
+ gr.Markdown("""
90
+ 1. Type your message in the input box
91
+ 2. Press Enter or click Send
92
+ 3. The AI will respond automatically
93
+ 4. Continue the conversation naturally
94
+ """)
95
+
96
+ clear_btn = gr.Button("🔄 Clear Chat", variant="secondary")
97
+
98
+ # Chatbot logic
99
+ def user_message(user_msg, history):
100
+ return "", history + [[user_msg, None]]
101
+
102
+ def bot_response(history):
103
+ user_msg = history[-1][0]
104
+ bot_msg = chatbot.respond(user_msg, history)
105
+ history[-1][1] = bot_msg
106
+ return history
107
+
108
+ # Event listeners
109
+ message_input.submit(
110
+ user_message,
111
+ [message_input, chatbot_interface],
112
+ [message_input, chatbot_interface],
113
+ queue=False
114
+ ).then(
115
+ bot_response,
116
+ [chatbot_interface],
117
+ [chatbot_interface]
118
+ )
119
+
120
+ clear_btn.click(
121
+ lambda: None,
122
+ None,
123
+ chatbot_interface,
124
+ queue=False
125
+ )
126
+
127
+ # Launch with custom theme and footer
128
+ demo.launch(
129
+ theme=custom_theme,
130
  footer_links=[
131
+ {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
132
+ {"label": "Gradio Docs", "url": "https://gradio.app/docs"}
133
+ ],
134
+ title="AI Chatbot",
135
+ description="A simple AI chatbot for conversation using Gradio"
136
  )