Update app.py
Browse files
app.py
CHANGED
@@ -1,11 +1,175 @@
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
from
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
def respond(
|
11 |
message,
|
@@ -13,52 +177,73 @@ def respond(
|
|
13 |
system_message,
|
14 |
max_tokens,
|
15 |
temperature,
|
16 |
-
top_p
|
17 |
):
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
-
|
26 |
-
messages.append({"role": "user", "content": message})
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
temperature=temperature,
|
35 |
-
top_p=top_p
|
36 |
-
)
|
37 |
-
token = message.choices[0].delta.content
|
38 |
|
39 |
-
|
40 |
-
|
|
|
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(
|
50 |
-
|
|
|
|
|
|
|
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.
|
56 |
step=0.05,
|
57 |
label="Top-p (nucleus sampling)",
|
58 |
),
|
59 |
],
|
60 |
)
|
61 |
|
62 |
-
|
63 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
demo.launch()
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import requests
|
4 |
import gradio as gr
|
5 |
+
from bs4 import BeautifulSoup
|
6 |
+
import torch
|
7 |
|
8 |
+
# Hugging Face Transformers
|
9 |
+
from transformers import (
|
10 |
+
AutoTokenizer,
|
11 |
+
AutoModelForCausalLM,
|
12 |
+
Trainer,
|
13 |
+
TrainingArguments,
|
14 |
+
pipeline
|
15 |
+
)
|
16 |
+
from datasets import Dataset
|
17 |
+
|
18 |
+
# -----------------------------
|
19 |
+
# 1) SCRAPING (OPTIONAL)
|
20 |
+
# -----------------------------
|
21 |
+
BASE_URL = "https://www.cia.gov"
|
22 |
+
ARCHIVE_URL = "https://www.cia.gov/resources/csi/studies-in-intelligence/archives/operations-subject-index/"
|
23 |
+
|
24 |
+
def get_article_links():
|
25 |
+
"""
|
26 |
+
Fetch the archive page and extract article links pointing to the CIA Studies in Intelligence.
|
27 |
+
"""
|
28 |
+
response = requests.get(ARCHIVE_URL)
|
29 |
+
response.raise_for_status()
|
30 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
31 |
+
|
32 |
+
links = []
|
33 |
+
for a_tag in soup.find_all('a', href=True):
|
34 |
+
href = a_tag['href']
|
35 |
+
if "resources/csi/studies-in-intelligence" in href.lower():
|
36 |
+
# Convert relative links to absolute
|
37 |
+
if href.startswith("/"):
|
38 |
+
href = BASE_URL + href
|
39 |
+
links.append(href)
|
40 |
+
|
41 |
+
return list(set(links)) # remove duplicates
|
42 |
+
|
43 |
+
def scrape_article_text(url):
|
44 |
+
"""
|
45 |
+
Fetch the article text from the URL if it's HTML.
|
46 |
+
(Skipping PDFs for demo.)
|
47 |
+
"""
|
48 |
+
response = requests.get(url)
|
49 |
+
response.raise_for_status()
|
50 |
+
content_type = response.headers.get('Content-Type', '')
|
51 |
+
if 'application/pdf' in content_type.lower():
|
52 |
+
# Skip PDFs in this simple demo.
|
53 |
+
return None
|
54 |
+
|
55 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
56 |
+
paragraphs = soup.find_all('p')
|
57 |
+
article_text = "\n".join(p.get_text(strip=True) for p in paragraphs)
|
58 |
+
return article_text
|
59 |
+
|
60 |
+
def scrape_all_articles(article_links):
|
61 |
+
"""
|
62 |
+
Iterate through all links and gather text into a dict {url: text}.
|
63 |
+
"""
|
64 |
+
corpus_data = {}
|
65 |
+
for link in article_links:
|
66 |
+
text = scrape_article_text(link)
|
67 |
+
if text:
|
68 |
+
corpus_data[link] = text
|
69 |
+
return corpus_data
|
70 |
+
|
71 |
+
# -----------------------------
|
72 |
+
# 2) DATA CLEANING
|
73 |
+
# -----------------------------
|
74 |
+
import re
|
75 |
+
|
76 |
+
def clean_text(text):
|
77 |
+
# Simple cleaning: remove extra whitespace
|
78 |
+
text = re.sub(r'\s+', ' ', text)
|
79 |
+
text = text.strip()
|
80 |
+
return text
|
81 |
+
|
82 |
+
def prepare_dataset(corpus_data):
|
83 |
+
cleaned_texts = []
|
84 |
+
for url, text in corpus_data.items():
|
85 |
+
cleaned_texts.append(clean_text(text))
|
86 |
+
return cleaned_texts
|
87 |
+
|
88 |
+
# -----------------------------
|
89 |
+
# 3) FINE-TUNING (OPTIONAL)
|
90 |
+
# -----------------------------
|
91 |
+
def fine_tune_model(cleaned_texts, model_name="gpt2", output_dir="cia_agent_model"):
|
92 |
+
"""
|
93 |
+
Fine-tunes GPT-2 on your CIA corpus.
|
94 |
+
Warning: resource-intensive! The free Hugging Face Spaces might time out.
|
95 |
+
"""
|
96 |
+
ds = Dataset.from_dict({"text": cleaned_texts})
|
97 |
+
|
98 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
99 |
+
tokenizer.pad_token = tokenizer.eos_token # GPT-2 doesn't have a pad token
|
100 |
+
|
101 |
+
def tokenize_function(examples):
|
102 |
+
return tokenizer(
|
103 |
+
examples["text"],
|
104 |
+
truncation=True,
|
105 |
+
padding="max_length",
|
106 |
+
max_length=128
|
107 |
+
)
|
108 |
|
109 |
+
tokenized_ds = ds.map(tokenize_function, batched=True)
|
110 |
+
|
111 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
112 |
+
|
113 |
+
training_args = TrainingArguments(
|
114 |
+
output_dir=output_dir,
|
115 |
+
overwrite_output_dir=True,
|
116 |
+
num_train_epochs=1, # demonstration only
|
117 |
+
per_device_train_batch_size=1,
|
118 |
+
save_steps=100,
|
119 |
+
save_total_limit=1,
|
120 |
+
logging_steps=10,
|
121 |
+
evaluation_strategy="no", # or 'steps'
|
122 |
+
)
|
123 |
+
|
124 |
+
trainer = Trainer(
|
125 |
+
model=model,
|
126 |
+
args=training_args,
|
127 |
+
train_dataset=tokenized_ds,
|
128 |
+
)
|
129 |
+
trainer.train()
|
130 |
+
|
131 |
+
trainer.save_model(output_dir)
|
132 |
+
tokenizer.save_pretrained(output_dir)
|
133 |
+
|
134 |
+
return model, tokenizer
|
135 |
+
|
136 |
+
# -----------------------------
|
137 |
+
# 4) CIAgent INFERENCE
|
138 |
+
# -----------------------------
|
139 |
+
class CIAgent:
|
140 |
+
def __init__(self, model_path="cia_agent_model"):
|
141 |
+
"""
|
142 |
+
Initialize a pipeline from a local fine-tuned model folder or fallback to GPT-2.
|
143 |
+
"""
|
144 |
+
if not os.path.exists(model_path):
|
145 |
+
model_path = "gpt2"
|
146 |
+
self.generator = pipeline(
|
147 |
+
"text-generation",
|
148 |
+
model=model_path,
|
149 |
+
tokenizer=model_path
|
150 |
+
)
|
151 |
+
self.max_length = 128
|
152 |
+
|
153 |
+
def query(self, prompt, max_length=128, temperature=0.7, top_p=0.9):
|
154 |
+
"""
|
155 |
+
Generate text from the model.
|
156 |
+
"""
|
157 |
+
outputs = self.generator(
|
158 |
+
prompt,
|
159 |
+
max_length=max_length,
|
160 |
+
temperature=temperature,
|
161 |
+
top_p=top_p,
|
162 |
+
num_return_sequences=1
|
163 |
+
)
|
164 |
+
return outputs[0]["generated_text"]
|
165 |
+
|
166 |
+
# -----------------------------
|
167 |
+
# 5) GRADIO CHAT INTERFACE
|
168 |
+
# -----------------------------
|
169 |
+
|
170 |
+
# Create (or load) your CIAgent. In a real workflow, you might have already
|
171 |
+
# fine-tuned locally and just upload the "cia_agent_model" folder to your Space.
|
172 |
+
agent = CIAgent(model_path="cia_agent_model") # or "gpt2" if you haven't trained
|
173 |
|
174 |
def respond(
|
175 |
message,
|
|
|
177 |
system_message,
|
178 |
max_tokens,
|
179 |
temperature,
|
180 |
+
top_p
|
181 |
):
|
182 |
+
"""
|
183 |
+
This function is called by Gradio's ChatInterface. It receives:
|
184 |
+
- message: current user message
|
185 |
+
- history: list of (user_text, assistant_text) pairs
|
186 |
+
- system_message: the "system" instruction to guide the model
|
187 |
+
- max_tokens, temperature, top_p: generation parameters
|
|
|
|
|
|
|
188 |
|
189 |
+
We build a 'prompt' from all conversation turns + system message.
|
190 |
+
Then we query the CIAgent to get one text output.
|
191 |
+
Since CIAgent doesn't stream tokens by default, we yield once at the end.
|
192 |
+
"""
|
193 |
+
# Build the conversation prompt
|
194 |
+
# For demonstration, we simply concatenate everything in a naive format.
|
195 |
+
# You could style it in a more advanced way for better context handling.
|
196 |
+
prompt = f"System: {system_message}\n\n"
|
197 |
+
for user_text, assistant_text in history:
|
198 |
+
if user_text:
|
199 |
+
prompt += f"User: {user_text}\n"
|
200 |
+
if assistant_text:
|
201 |
+
prompt += f"Assistant: {assistant_text}\n"
|
202 |
+
# Add the new user message
|
203 |
+
prompt += f"User: {message}\nAssistant: "
|
204 |
|
205 |
+
# Query the local CIAgent
|
206 |
+
response_text = agent.query(
|
207 |
+
prompt,
|
208 |
+
max_length=max_tokens,
|
209 |
temperature=temperature,
|
210 |
+
top_p=top_p
|
211 |
+
)
|
|
|
212 |
|
213 |
+
# We can yield partial tokens if we want streaming, but the pipeline
|
214 |
+
# returns the entire text at once. Let's yield a single chunk:
|
215 |
+
yield response_text
|
216 |
|
217 |
+
# Create the ChatInterface
|
|
|
|
|
|
|
218 |
demo = gr.ChatInterface(
|
219 |
+
fn=respond,
|
220 |
additional_inputs=[
|
221 |
+
gr.Textbox(
|
222 |
+
value="You are a friendly Chatbot that knows about CIA Studies in Intelligence.",
|
223 |
+
label="System message"
|
224 |
+
),
|
225 |
+
gr.Slider(minimum=1, maximum=2048, value=256, step=1, label="Max new tokens"),
|
226 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
227 |
gr.Slider(
|
228 |
minimum=0.1,
|
229 |
maximum=1.0,
|
230 |
+
value=0.9,
|
231 |
step=0.05,
|
232 |
label="Top-p (nucleus sampling)",
|
233 |
),
|
234 |
],
|
235 |
)
|
236 |
|
|
|
237 |
if __name__ == "__main__":
|
238 |
+
# WARNING: Running scraping & fine-tuning on a free HF Space
|
239 |
+
# might exceed time/memory limits. If you do want to train, uncomment:
|
240 |
+
#
|
241 |
+
# article_links = get_article_links()
|
242 |
+
# corpus_data = scrape_all_articles(article_links)
|
243 |
+
# cleaned_texts = prepare_dataset(corpus_data)
|
244 |
+
# model, tokenizer = fine_tune_model(cleaned_texts)
|
245 |
+
#
|
246 |
+
# Then re-initialize agent = CIAgent("cia_agent_model")
|
247 |
+
#
|
248 |
+
# For now, just launch the Gradio chat using the existing or fallback GPT-2 model.
|
249 |
demo.launch()
|