vincentclaes commited on
Commit
60e3b0a
1 Parent(s): f9f7dff

preliminary code for a website

Browse files
Files changed (4) hide show
  1. README.md +13 -1
  2. app.py +160 -0
  3. requirements.txt +6 -0
  4. scrape_website.py +49 -0
README.md CHANGED
@@ -1,2 +1,14 @@
1
- # faq-website
 
 
 
 
 
 
 
 
 
 
 
 
2
  repo for the code to QA content form a website
 
1
+ ---
2
+ title: FAQ a Website
3
+ emoji: 🦙
4
+ colorFrom: white
5
+ colorTo: gray
6
+ sdk: gradio
7
+ sdk_version: 3.21.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
12
+
13
+ # Faq A website
14
  repo for the code to QA content form a website
app.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from peft import PeftModel
3
+ import transformers
4
+ import gradio as gr
5
+
6
+ assert (
7
+ "LlamaTokenizer" in transformers._import_structure["models.llama"]
8
+ ), "LLaMA is now in HuggingFace's main branch.\nPlease reinstall it: pip uninstall transformers && pip install git+https://github.com/huggingface/transformers.git"
9
+ from transformers import LlamaTokenizer, LlamaForCausalLM, GenerationConfig
10
+
11
+ tokenizer = LlamaTokenizer.from_pretrained("decapoda-research/llama-7b-hf")
12
+
13
+ BASE_MODEL = "decapoda-research/llama-7b-hf"
14
+ LORA_WEIGHTS = "tloen/alpaca-lora-7b"
15
+
16
+ if torch.cuda.is_available():
17
+ device = "cuda"
18
+ else:
19
+ device = "cpu"
20
+
21
+ try:
22
+ if torch.backends.mps.is_available():
23
+ device = "mps"
24
+ except:
25
+ pass
26
+
27
+ if device == "cuda":
28
+ model = LlamaForCausalLM.from_pretrained(
29
+ BASE_MODEL,
30
+ load_in_8bit=False,
31
+ torch_dtype=torch.float16,
32
+ device_map="auto",
33
+ )
34
+ model = PeftModel.from_pretrained(
35
+ model, LORA_WEIGHTS, torch_dtype=torch.float16, force_download=True
36
+ )
37
+ elif device == "mps":
38
+ model = LlamaForCausalLM.from_pretrained(
39
+ BASE_MODEL,
40
+ device_map={"": device},
41
+ torch_dtype=torch.float16,
42
+ )
43
+ model = PeftModel.from_pretrained(
44
+ model,
45
+ LORA_WEIGHTS,
46
+ device_map={"": device},
47
+ torch_dtype=torch.float16,
48
+ )
49
+ else:
50
+ model = LlamaForCausalLM.from_pretrained(
51
+ BASE_MODEL, device_map={"": device}, low_cpu_mem_usage=True
52
+ )
53
+ model = PeftModel.from_pretrained(
54
+ model,
55
+ LORA_WEIGHTS,
56
+ device_map={"": device},
57
+ )
58
+
59
+
60
+ def generate_prompt(instruction, input=None):
61
+ if input:
62
+ return f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
63
+ ### Instruction:
64
+ {instruction}
65
+ ### Input:
66
+ {input}
67
+ ### Response:"""
68
+ else:
69
+ return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
70
+ ### Instruction:
71
+ {instruction}
72
+ ### Response:"""
73
+
74
+ if device != "cpu":
75
+ model.half()
76
+ model.eval()
77
+ if torch.__version__ >= "2":
78
+ model = torch.compile(model)
79
+
80
+
81
+ def evaluate(
82
+ instruction,
83
+ input=None,
84
+ temperature=0.1,
85
+ top_p=0.75,
86
+ top_k=40,
87
+ num_beams=4,
88
+ max_new_tokens=128,
89
+ **kwargs,
90
+ ):
91
+ prompt = generate_prompt(instruction, input)
92
+ inputs = tokenizer(prompt, return_tensors="pt")
93
+ input_ids = inputs["input_ids"].to(device)
94
+ generation_config = GenerationConfig(
95
+ temperature=temperature,
96
+ top_p=top_p,
97
+ top_k=top_k,
98
+ num_beams=num_beams,
99
+ **kwargs,
100
+ )
101
+ with torch.no_grad():
102
+ generation_output = model.generate(
103
+ input_ids=input_ids,
104
+ generation_config=generation_config,
105
+ return_dict_in_generate=True,
106
+ output_scores=True,
107
+ max_new_tokens=max_new_tokens,
108
+ )
109
+ s = generation_output.sequences[0]
110
+ output = tokenizer.decode(s)
111
+ return output.split("### Response:")[1].strip()
112
+
113
+
114
+ g = gr.Interface(
115
+ fn=evaluate,
116
+ inputs=[
117
+ gr.components.Textbox(
118
+ lines=2, label="Instruction", placeholder="Tell me about alpacas."
119
+ ),
120
+ gr.components.Textbox(lines=2, label="Input", placeholder="none"),
121
+ gr.components.Slider(minimum=0, maximum=1, value=0.1, label="Temperature"),
122
+ gr.components.Slider(minimum=0, maximum=1, value=0.75, label="Top p"),
123
+ gr.components.Slider(minimum=0, maximum=100, step=1, value=40, label="Top k"),
124
+ gr.components.Slider(minimum=1, maximum=4, step=1, value=4, label="Beams"),
125
+ gr.components.Slider(
126
+ minimum=1, maximum=512, step=1, value=128, label="Max tokens"
127
+ ),
128
+ ],
129
+ outputs=[
130
+ gr.inputs.Textbox(
131
+ lines=5,
132
+ label="Output",
133
+ )
134
+ ],
135
+ title="🦙🌲 Alpaca-LoRA",
136
+ description="Alpaca-LoRA is a 7B-parameter LLaMA model finetuned to follow instructions. It is trained on the [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca) dataset and makes use of the Huggingface LLaMA implementation. For more information, please visit [the project's website](https://github.com/tloen/alpaca-lora).",
137
+ )
138
+ g.queue(concurrency_count=1)
139
+ g.launch()
140
+
141
+ # Old testing code follows.
142
+
143
+ """
144
+ if __name__ == "__main__":
145
+ # testing code for readme
146
+ for instruction in [
147
+ "Tell me about alpacas.",
148
+ "Tell me about the president of Mexico in 2019.",
149
+ "Tell me about the king of France in 2019.",
150
+ "List all Canadian provinces in alphabetical order.",
151
+ "Write a Python program that prints the first 10 Fibonacci numbers.",
152
+ "Write a program that prints the numbers from 1 to 100. But for multiples of three print 'Fizz' instead of the number and for the multiples of five print 'Buzz'. For numbers which are multiples of both three and five print 'FizzBuzz'.",
153
+ "Tell me five words that rhyme with 'shock'.",
154
+ "Translate the sentence 'I have no mouth but I must scream' into Spanish.",
155
+ "Count up from 1 to 500.",
156
+ ]:
157
+ print("Instruction:", instruction)
158
+ print("Response:", evaluate(instruction))
159
+ print()
160
+ """
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ beautifulsoup4
2
+ requests
3
+ torch
4
+ transformers
5
+ peft
6
+ gradio
scrape_website.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+
4
+ def process_webpage(url:str):
5
+ # A set to keep track of visited pages
6
+ visited_pages = set()
7
+
8
+ text_list = []
9
+
10
+ # A function to recursively get all child pages
11
+ def get_child_pages(url):
12
+ # Make a GET request to the page and get the HTML content
13
+ response = requests.get(url)
14
+ html_content = response.content
15
+
16
+ # Parse the HTML content using BeautifulSoup
17
+ soup = BeautifulSoup(html_content, "html.parser")
18
+
19
+ # Get all the text content from the relevant HTML tags
20
+ text_content = ""
21
+ for tag in ["p", "h1", "h2", "h3", "h4", "h5", "h6", "li"]:
22
+ for element in soup.find_all(tag):
23
+ text_content += element.get_text() + " "
24
+
25
+ # Add the page to the set of visited pages
26
+ text_content = f"page {url} contains: " + text_content
27
+ visited_pages.add(url)
28
+
29
+ # Find all the child links and recursively get their text content
30
+ for link in soup.find_all("a"):
31
+ href = link.get("href")
32
+ if href and href not in visited_pages and url in href:
33
+ get_child_pages(href)
34
+
35
+ text_list.append(text_content)
36
+
37
+ # Get the text content of the landing page
38
+ get_child_pages(url)
39
+
40
+ # make main page as first item
41
+ text_list.reverse()
42
+
43
+ page_content = "\n".join(text_list)
44
+ # Print the text content of the landing page and all child pages
45
+ print(page_content)
46
+
47
+
48
+ if __name__ == '__main__':
49
+ process_webpage(url="https://www.meet-drift.ai/")