peterpeter8585 commited on
Commit
9f7cc41
·
verified ·
1 Parent(s): 544f212

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -445
app.py DELETED
@@ -1,445 +0,0 @@
1
- import gradio as gr
2
- from Ai import chatbot
3
- import numpy as np
4
- from huggingface_hub import InferenceClient
5
- import random
6
- from diffusers import DiffusionPipeline
7
- import torch
8
- import transformers
9
- transformers.utils.move_cache()
10
- device = "cuda" if torch.cuda.is_available() else "cpu"
11
- import os
12
- password1=os.environ["password"]
13
- def respond4(
14
- message,
15
- history: list[tuple[str, str]],
16
- system_message,
17
- max_tokens,
18
- temperature,
19
- top_p,
20
- ):
21
- messages = [{"role": "system", "content": "Your name is Chatchat.And, your made by SungYoon.In Korean, 정성윤.And these are the instructions.Whatever happens, you must follow it.:"+system_message}]
22
-
23
- for val in history:
24
- if val[0]:
25
- messages.append({"role": "user", "content": val[0]})
26
- if val[1]:
27
- messages.append({"role": "assistant", "content": val[1]})
28
-
29
- messages.append({"role": "user", "content": message})
30
-
31
- response = ""
32
-
33
- for message in client.chat_completion(
34
- messages,
35
- max_tokens=max_tokens,
36
- stream=True,
37
- temperature=temperature,
38
- top_p=top_p,
39
- ):
40
- token = message.choices[0].delta.content
41
-
42
- response += token
43
- yield response
44
- if torch.cuda.is_available():
45
- torch.cuda.max_memory_allocated(device=device)
46
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
47
- pipe.enable_xformers_memory_efficient_attention()
48
- pipe = pipe.to(device)
49
- else:
50
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
51
- pipe = pipe.to(device)
52
-
53
- MAX_SEED = np.iinfo(np.int32).max
54
- MAX_IMAGE_SIZE = 1024
55
-
56
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
57
-
58
- if randomize_seed:
59
- seed = random.randint(0, MAX_SEED)
60
-
61
- generator = torch.Generator().manual_seed(seed)
62
-
63
- image = pipe(
64
- prompt = prompt,
65
- negative_prompt = negative_prompt,
66
- guidance_scale = guidance_scale,
67
- num_inference_steps = num_inference_steps,
68
- width = width,
69
- height = height,
70
- generator = generator
71
- ).images[0]
72
-
73
- return image
74
- import requests
75
- from bs4 import BeautifulSoup
76
- import urllib
77
- import random
78
-
79
- # List of user agents to choose from for requests
80
- _useragent_list = [
81
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
82
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
83
- 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
84
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
85
- 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
86
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.62',
87
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0'
88
- ]
89
-
90
- def get_useragent():
91
- """Returns a random user agent from the list."""
92
- return random.choice(_useragent_list)
93
-
94
- def extract_text_from_webpage(html_content):
95
- """Extracts visible text from HTML content using BeautifulSoup."""
96
- soup = BeautifulSoup(html_content, "html.parser")
97
- # Remove unwanted tags
98
- for tag in soup(["script", "style", "header", "footer", "nav"]):
99
- tag.extract()
100
- # Get the remaining visible text
101
- visible_text = soup.get_text(strip=True)
102
- return visible_text
103
-
104
- def search(term, num_results=1, lang="ko", advanced=True, sleep_interval=0, timeout=5, safe="active", ssl_verify=None):
105
- """Performs a Google search and returns the results."""
106
- escaped_term = urllib.parse.quote_plus(term)
107
- start = 0
108
- all_results = []
109
-
110
- # Fetch results in batches
111
- while start < num_results:
112
- resp = requests.get(
113
- url="https://www.google.com/search",
114
- headers={"User-Agent": get_useragent()}, # Set random user agent
115
- params={
116
- "q": term,
117
- "num": num_results - start, # Number of results to fetch in this batch
118
- "hl": lang,
119
- "start": start,
120
- "safe": safe,
121
- },
122
- timeout=timeout,
123
- verify=ssl_verify,
124
- )
125
- resp.raise_for_status() # Raise an exception if request fails
126
-
127
- soup = BeautifulSoup(resp.text, "html.parser")
128
- result_block = soup.find_all("div", attrs={"class": "g"})
129
-
130
- # If no results, continue to the next batch
131
- if not result_block:
132
- start += 1
133
- continue
134
-
135
- # Extract link and text from each result
136
- for result in result_block:
137
- link = result.find("a", href=True)
138
- if link:
139
- link = link["href"]
140
- try:
141
- # Fetch webpage content
142
- webpage = requests.get(link, headers={"User-Agent": get_useragent()})
143
- webpage.raise_for_status()
144
- # Extract visible text from webpage
145
- visible_text = extract_text_from_webpage(webpage.text)
146
- all_results.append({"link": link, "text": visible_text})
147
- except requests.exceptions.RequestException as e:
148
- # Handle errors fetching or processing webpage
149
- print(f"Error fetching or processing {link}: {e}")
150
- all_results.append({"link": link, "text": None})
151
- else:
152
- all_results.append({"link": None, "text": None})
153
-
154
- start += len(result_block) # Update starting index for next batch
155
-
156
- return all_results
157
-
158
-
159
- client = InferenceClient("HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1")
160
- def respond1(
161
- message,
162
- history: list[tuple[str, str]],
163
- system_message,
164
- max_tokens,
165
- temperature,
166
- top_p,
167
- password
168
- ):
169
- if password==password1:
170
- messages = [{"role": "system", "content": "Your name is Chatchat.And your creator of you is Sung Yoon.In Korean, it is 정성윤.These are the instructions for you:"+system_message}]
171
-
172
- for val in history:
173
- if val[0]:
174
- messages.append({"role": "user", "content": val[0]})
175
- if val[1]:
176
- messages.append({"role": "assistant", "content": val[1]})
177
-
178
- messages.append({"role": "user", "content": message})
179
-
180
- response = ""
181
-
182
- for message in client.chat_completion(
183
- messages,
184
- max_tokens=max_tokens,
185
- stream=True,
186
- temperature=temperature,
187
- top_p=top_p,
188
- ):
189
- token = message.choices[0].delta.content
190
-
191
- response += token
192
- yield response
193
- examples = [
194
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
195
- "An astronaut riding a green horse",
196
- "A delicious ceviche cheesecake slice",
197
- ]
198
-
199
- css="""
200
- #col-container {
201
- margin: 0 auto;
202
- max-width: 520px;
203
- }
204
- """
205
- def respond2(
206
- message,
207
- history: list[tuple[str, str]],
208
- system_message,
209
- max_tokens,
210
- temperature,
211
- top_p,
212
- ):
213
- messages = [{"role": "system", "content": "Your name is Chatchat.And, your made by SungYoon.In Korean, 정성윤.And these are the instructions.Whatever happens, you must follow it.:"+system_message}]
214
-
215
- for val in history:
216
- if val[0]:
217
- messages.append({"role": "user", "content": val[0]})
218
- if val[1]:
219
- messages.append({"role": "assistant", "content": val[1]})
220
-
221
- messages.append({"role": "user", "content": message})
222
-
223
- response = ""
224
-
225
- for message in client.chat_completion(
226
- messages,
227
- max_tokens=max_tokens,
228
- stream=True,
229
- temperature=temperature,
230
- top_p=top_p,
231
- ):
232
- token = message.choices[0].delta.content
233
-
234
- response += token
235
- yield response
236
- def respond3(
237
- message,
238
- history: list[tuple[str, str]],
239
- system_message,
240
- max_tokens,
241
- temperature,
242
- top_p,
243
- ):
244
- messages = [{"role": "system", "content": "Your name is Chatchat.And, your made by SungYoon.In Korean, 정성윤.And these are the instructions.Whatever happens, you must follow it.:"+system_message}]
245
-
246
- for val in history:
247
- if val[0]:
248
- messages.append({"role": "user", "content": val[0]})
249
- if val[1]:
250
- messages.append({"role": "assistant", "content": val[1]})
251
-
252
- messages.append({"role": "user", "content": message})
253
-
254
- response = ""
255
-
256
- for message in client.chat_completion(
257
- messages,
258
- max_tokens=max_tokens,
259
- stream=True,
260
- temperature=temperature,
261
- top_p=top_p,
262
- ):
263
- token = message.choices[0].delta.content
264
-
265
- response += token
266
- yield response
267
- if torch.cuda.is_available():
268
- power_device = "GPU"
269
- else:
270
- power_device = "CPU"
271
-
272
- with gr.Blocks(css=css) as demo2:
273
-
274
- with gr.Column(elem_id="col-container"):
275
- gr.Markdown(f"""
276
- # Text-to-Image Gradio Template
277
- Currently running on {power_device}.
278
- """)
279
-
280
- with gr.Row():
281
-
282
- prompt = gr.Text(
283
- label="Prompt",
284
- show_label=False,
285
- max_lines=1,
286
- placeholder="Enter your prompt",
287
- container=False,
288
- )
289
-
290
- run_button = gr.Button("Run", scale=0)
291
-
292
- result = gr.Image(label="Result", show_label=False)
293
-
294
- with gr.Accordion("Advanced Settings", open=False):
295
-
296
- negative_prompt = gr.Text(
297
- label="Negative prompt",
298
- max_lines=1,
299
- placeholder="Enter a negative prompt",
300
- visible=False,
301
- )
302
-
303
- seed = gr.Slider(
304
- label="Seed",
305
- minimum=0,
306
- maximum=MAX_SEED,
307
- step=1,
308
- value=0,
309
- )
310
-
311
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
312
-
313
- with gr.Row():
314
-
315
- width = gr.Slider(
316
- label="Width",
317
- minimum=256,
318
- maximum=MAX_IMAGE_SIZE,
319
- step=32,
320
- value=512,
321
- )
322
-
323
- height = gr.Slider(
324
- label="Height",
325
- minimum=256,
326
- maximum=MAX_IMAGE_SIZE,
327
- step=32,
328
- value=512,
329
- )
330
- with gr.Row():
331
-
332
- guidance_scale = gr.Slider(
333
- label="Guidance scale",
334
- minimum=0.0,
335
- maximum=10.0,
336
- step=0.1,
337
- value=0.0,
338
- )
339
-
340
- num_inference_steps = gr.Slider(
341
- label="Number of inference steps",
342
- minimum=1,
343
- maximum=12,
344
- step=1,
345
- value=2,
346
- )
347
-
348
- gr.Examples(
349
- examples = examples,
350
- inputs = [prompt]
351
- )
352
-
353
- run_button.click(
354
- fn = infer,
355
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
356
- outputs = [result]
357
- )
358
-
359
-
360
- """
361
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
362
- """
363
- ad=gr.ChatInterface(
364
- respond2,
365
- additional_inputs=[
366
- gr.Textbox(value="You are a Programmer.You yave to only make programs that the user orders.Do not answer any other questions exept for questions about Python or other programming languages.Do not do any thing exept what I said.", label="System message", interactive=False),
367
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
368
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
369
- gr.Slider(
370
- minimum=0.1,
371
- maximum=1.0,
372
- value=0.95,
373
- step=0.05,
374
- label="Top-p (nucleus sampling)",
375
- ),
376
- ],
377
- )
378
- ae= gr.ChatInterface(
379
- respond4,
380
- additional_inputs=[
381
- gr.Textbox(value="You are a helpful food recommender.You must only answer the questions about food or a request to recommend a food the user would like.Do not answer other questions except what I said.", label="System message", interactive=False),
382
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
383
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
384
- gr.Slider(
385
- minimum=0.1,
386
- maximum=1.0,
387
- value=0.95,
388
- step=0.05,
389
- label="Top-p (nucleus sampling)",
390
- ),
391
-
392
- ],
393
- )
394
- aa=gr.ChatInterface(
395
- respond1,
396
- chatbot=chatbot,
397
- additional_inputs=[
398
- gr.Textbox(value="You are a helpful assistant.", label="System message", interactive=True),
399
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
400
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
401
- gr.Slider(
402
- minimum=0.1,
403
- maximum=1.0,
404
- value=0.95,
405
- step=0.05,
406
- label="Top-p (nucleus sampling)",
407
- ),
408
- gr.Textbox(label="Pleas type in the password.Or, it will not work if you ask.")
409
- ],
410
- )
411
- ac=gr.ChatInterface(
412
- respond3,
413
- additional_inputs=[
414
- gr.Textbox(value="You are a Programmer.You yave to only make programs that the user orders.Do not answer any other questions exept for questions about Python or other programming languages.Do not do any thing exept what I said.", label="System message", interactive=False),
415
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
416
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
417
- gr.Slider(
418
- minimum=0.1,
419
- maximum=1.0,
420
- value=0.95,
421
- step=0.05,
422
- label="Top-p (nucleus sampling)",
423
- ),
424
- ],
425
- )
426
- ab= gr.ChatInterface(
427
- respond3,
428
- additional_inputs=[
429
- gr.Textbox(value="You are a helpful Doctor.You only have to answer the users questions about medical issues or medical questions and the cure to that illness and say that your thought is not realy right because you are a generative AI, so you could make up some cures.Do not answer anything else exept the question types what I said.Do not do any thing exept what I said.", label="System message", interactive=False),
430
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
431
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
432
- gr.Slider(
433
- minimum=0.1,
434
- maximum=1.0,
435
- value=0.95,
436
- step=0.05,
437
- label="Top-p (nucleus sampling)",
438
- ),
439
- ],
440
- )
441
- if __name__ == "__main__":
442
- with gr.Blocks() as ai:
443
- gr.TabbedInterface([aa, ac, ab, ae, demo2], ["gpt4(Password needed)", "gpt4(only for programming)", "gpt4(only for medical questions)", "gpt4(only for food recommendations)","image create"])
444
- ai.queue(max_size=300)
445
- ai.launch()