limitedonly41 commited on
Commit
aa24a46
Β·
verified Β·
1 Parent(s): 1531e35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -36
app.py CHANGED
@@ -17,6 +17,10 @@ dtype = None
17
  load_in_4bit = True
18
  peft_model_name = "limitedonly41/mistral7b_v3_4_categories"
19
 
 
 
 
 
20
  def translate_text(text: str) -> str:
21
  """Translate text to English"""
22
  try:
@@ -28,22 +32,29 @@ def translate_text(text: str) -> str:
28
  return text[:4990]
29
 
30
  @spaces.GPU
31
- def predict_inference(translated_text: str) -> str:
32
  """GPU-accelerated inference function"""
 
 
33
  try:
34
  if len(translated_text) < 150:
35
- return 'Short'
36
-
37
- from unsloth import FastLanguageModel
38
 
39
- # Load model INSIDE the GPU function
40
- model, tokenizer = FastLanguageModel.from_pretrained(
41
- model_name=peft_model_name,
42
- max_seq_length=max_seq_length,
43
- dtype=dtype,
44
- load_in_4bit=load_in_4bit,
45
- )
46
- FastLanguageModel.for_inference(model)
 
 
 
 
 
 
 
47
 
48
  prompt = 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.
49
 
@@ -58,24 +69,30 @@ Categorize the website into one of the 4 categories:\n\n1) OTHER\n2) NEWS/BLOG\n
58
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
59
 
60
  with autocast(device_type='cuda'):
61
- inputs = tokenizer(prompt, return_tensors="pt").to(device)
62
- outputs = model.generate(**inputs, max_new_tokens=16, use_cache=True)
63
- ans = tokenizer.batch_decode(outputs)[0]
64
 
 
65
  ans_pred = ans.split('### Response:')[1].split('<')[0].strip()
66
 
 
67
  if 'OTHER' in ans_pred:
68
- return 'OTHER'
69
  elif 'NEWS/BLOG' in ans_pred:
70
- return 'NEWS/BLOG'
71
  elif 'E-commerce' in ans_pred:
72
- return 'E-commerce'
 
 
73
  else:
74
- return 'ERROR'
 
 
75
 
76
  except Exception as e:
77
  print(f"Inference error: {e}")
78
- return 'ERROR'
79
 
80
  def scrape_url_with_curl_cffi(url: str) -> Tuple[str, str]:
81
  """Scrape URL using curl_cffi for better compatibility"""
@@ -125,10 +142,10 @@ def scrape_url_with_curl_cffi(url: str) -> Tuple[str, str]:
125
  except Exception as e:
126
  return f"Scraping error: {str(e)[:200]}", ""
127
 
128
- def process_single_url(url: str, progress=gr.Progress()) -> Tuple[str, str]:
129
- """Process a single URL and return both scraped text and prediction"""
130
  if not url.strip():
131
- return "Please provide a URL to process.", ""
132
 
133
  # Clean the URL
134
  url = url.strip()
@@ -142,10 +159,10 @@ def process_single_url(url: str, progress=gr.Progress()) -> Tuple[str, str]:
142
  status, scraped_text = scrape_url_with_curl_cffi(url)
143
 
144
  if status != "success":
145
- return status, ""
146
 
147
  if len(scraped_text) < 50:
148
- return "Error: Could not extract meaningful content from the website", scraped_text[:2000]
149
 
150
  # Limit text length for display
151
  scraped_display = scraped_text[:2000] + "..." if len(scraped_text) > 2000 else scraped_text
@@ -154,7 +171,7 @@ def process_single_url(url: str, progress=gr.Progress()) -> Tuple[str, str]:
154
 
155
  # Check if text is too short for classification
156
  if len(scraped_text) < 150:
157
- return "Short", scraped_display
158
 
159
  # Translate text
160
  translated = translate_text(scraped_text[:4990])
@@ -162,15 +179,15 @@ def process_single_url(url: str, progress=gr.Progress()) -> Tuple[str, str]:
162
  progress(0.7, desc="Classifying website...")
163
 
164
  # Get prediction using GPU
165
- prediction = predict_inference(translated)
166
 
167
  progress(1.0, desc="Complete!")
168
 
169
- return prediction, scraped_display
170
 
171
  except Exception as e:
172
  error_msg = f"Error processing URL: {str(e)[:200]}"
173
- return error_msg, ""
174
 
175
  def create_interface():
176
  with gr.Blocks(title="Website Category Classifier", theme=gr.themes.Soft()) as interface:
@@ -178,7 +195,7 @@ def create_interface():
178
  <div style="text-align: center; margin-bottom: 20px;">
179
  <h1>πŸ” Website Category Classifier</h1>
180
  <p style="font-size: 18px; color: #666;">
181
- Classify websites into categories: <strong>OTHER</strong>, <strong>NEWS/BLOG</strong>, or <strong>E-commerce</strong>
182
  </p>
183
  </div>
184
  """)
@@ -207,7 +224,9 @@ def create_interface():
207
  ["https://amazon.com"],
208
  ["https://github.com"],
209
  ["https://cnn.com"],
210
- ["https://shopify.com"]
 
 
211
  ],
212
  inputs=[url_input],
213
  label="πŸ“‹ Try these examples:"
@@ -215,16 +234,23 @@ def create_interface():
215
 
216
  with gr.Column(scale=2):
217
  prediction_output = gr.Textbox(
218
- label="🎯 Classification Result",
219
- lines=3,
220
  interactive=False,
221
  info="The predicted category for this website"
222
  )
223
 
 
 
 
 
 
 
 
224
  scraped_output = gr.Textbox(
225
  label="πŸ“„ Scraped Content Preview (first 2000 characters)",
226
- lines=20,
227
- max_lines=25,
228
  interactive=False,
229
  info="Raw text content extracted from the website"
230
  )
@@ -242,6 +268,7 @@ def create_interface():
242
  <ul>
243
  <li><strong>NEWS/BLOG:</strong> News websites, blogs, articles, journalism sites</li>
244
  <li><strong>E-commerce:</strong> Online stores, shopping sites, marketplaces</li>
 
245
  <li><strong>OTHER:</strong> All other types of websites (documentation, portfolios, etc.)</li>
246
  </ul>
247
  </div>
@@ -250,7 +277,7 @@ def create_interface():
250
  process_btn.click(
251
  fn=process_single_url,
252
  inputs=[url_input],
253
- outputs=[prediction_output, scraped_output],
254
  show_progress=True
255
  )
256
 
 
17
  load_in_4bit = True
18
  peft_model_name = "limitedonly41/mistral7b_v3_4_categories"
19
 
20
+ # Global variables to cache model and tokenizer
21
+ cached_model = None
22
+ cached_tokenizer = None
23
+
24
  def translate_text(text: str) -> str:
25
  """Translate text to English"""
26
  try:
 
32
  return text[:4990]
33
 
34
  @spaces.GPU
35
+ def predict_inference(translated_text: str) -> Tuple[str, str]:
36
  """GPU-accelerated inference function"""
37
+ global cached_model, cached_tokenizer
38
+
39
  try:
40
  if len(translated_text) < 150:
41
+ return 'Short', 'Text too short for classification'
 
 
42
 
43
+ # Load model only once (cache it globally)
44
+ if cached_model is None or cached_tokenizer is None:
45
+ print("Loading model for the first time...")
46
+ from unsloth import FastLanguageModel
47
+
48
+ cached_model, cached_tokenizer = FastLanguageModel.from_pretrained(
49
+ model_name=peft_model_name,
50
+ max_seq_length=max_seq_length,
51
+ dtype=dtype,
52
+ load_in_4bit=load_in_4bit,
53
+ )
54
+ FastLanguageModel.for_inference(cached_model)
55
+ print("Model loaded and cached successfully!")
56
+ else:
57
+ print("Using cached model...")
58
 
59
  prompt = 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.
60
 
 
69
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
70
 
71
  with autocast(device_type='cuda'):
72
+ inputs = cached_tokenizer(prompt, return_tensors="pt").to(device)
73
+ outputs = cached_model.generate(**inputs, max_new_tokens=16, use_cache=True)
74
+ ans = cached_tokenizer.batch_decode(outputs)[0]
75
 
76
+ # Extract the raw prediction
77
  ans_pred = ans.split('### Response:')[1].split('<')[0].strip()
78
 
79
+ # Process the prediction into final category
80
  if 'OTHER' in ans_pred:
81
+ final_prediction = 'OTHER'
82
  elif 'NEWS/BLOG' in ans_pred:
83
+ final_prediction = 'NEWS/BLOG'
84
  elif 'E-commerce' in ans_pred:
85
+ final_prediction = 'E-commerce'
86
+ elif 'COMPANIES' in ans_pred:
87
+ final_prediction = 'COMPANIES'
88
  else:
89
+ final_prediction = 'ERROR'
90
+
91
+ return final_prediction, ans_pred
92
 
93
  except Exception as e:
94
  print(f"Inference error: {e}")
95
+ return 'ERROR', f'Error: {str(e)[:200]}'
96
 
97
  def scrape_url_with_curl_cffi(url: str) -> Tuple[str, str]:
98
  """Scrape URL using curl_cffi for better compatibility"""
 
142
  except Exception as e:
143
  return f"Scraping error: {str(e)[:200]}", ""
144
 
145
+ def process_single_url(url: str, progress=gr.Progress()) -> Tuple[str, str, str]:
146
+ """Process a single URL and return prediction, raw prediction, and scraped text"""
147
  if not url.strip():
148
+ return "Please provide a URL to process.", "", ""
149
 
150
  # Clean the URL
151
  url = url.strip()
 
159
  status, scraped_text = scrape_url_with_curl_cffi(url)
160
 
161
  if status != "success":
162
+ return status, "", ""
163
 
164
  if len(scraped_text) < 50:
165
+ return "Error: Could not extract meaningful content from the website", "", scraped_text[:2000]
166
 
167
  # Limit text length for display
168
  scraped_display = scraped_text[:2000] + "..." if len(scraped_text) > 2000 else scraped_text
 
171
 
172
  # Check if text is too short for classification
173
  if len(scraped_text) < 150:
174
+ return "Short", "Text too short", scraped_display
175
 
176
  # Translate text
177
  translated = translate_text(scraped_text[:4990])
 
179
  progress(0.7, desc="Classifying website...")
180
 
181
  # Get prediction using GPU
182
+ prediction, raw_prediction = predict_inference(translated)
183
 
184
  progress(1.0, desc="Complete!")
185
 
186
+ return prediction, raw_prediction, scraped_display
187
 
188
  except Exception as e:
189
  error_msg = f"Error processing URL: {str(e)[:200]}"
190
+ return error_msg, "", ""
191
 
192
  def create_interface():
193
  with gr.Blocks(title="Website Category Classifier", theme=gr.themes.Soft()) as interface:
 
195
  <div style="text-align: center; margin-bottom: 20px;">
196
  <h1>πŸ” Website Category Classifier</h1>
197
  <p style="font-size: 18px; color: #666;">
198
+ Classify websites into categories: <strong>OTHER</strong>, <strong>NEWS/BLOG</strong>, <strong>E-commerce</strong>, <strong>COMPANIES</strong>
199
  </p>
200
  </div>
201
  """)
 
224
  ["https://amazon.com"],
225
  ["https://github.com"],
226
  ["https://cnn.com"],
227
+ ["https://shopify.com"],
228
+ ["https://apple.com"],
229
+ ["https://microsoft.com"]
230
  ],
231
  inputs=[url_input],
232
  label="πŸ“‹ Try these examples:"
 
234
 
235
  with gr.Column(scale=2):
236
  prediction_output = gr.Textbox(
237
+ label="🎯 Final Classification Result",
238
+ lines=2,
239
  interactive=False,
240
  info="The predicted category for this website"
241
  )
242
 
243
+ raw_prediction_output = gr.Textbox(
244
+ label="πŸ€– Raw Model Prediction",
245
+ lines=2,
246
+ interactive=False,
247
+ info="The exact text output from the AI model"
248
+ )
249
+
250
  scraped_output = gr.Textbox(
251
  label="πŸ“„ Scraped Content Preview (first 2000 characters)",
252
+ lines=15,
253
+ max_lines=20,
254
  interactive=False,
255
  info="Raw text content extracted from the website"
256
  )
 
268
  <ul>
269
  <li><strong>NEWS/BLOG:</strong> News websites, blogs, articles, journalism sites</li>
270
  <li><strong>E-commerce:</strong> Online stores, shopping sites, marketplaces</li>
271
+ <li><strong>COMPANIES:</strong> Corporate websites, business pages, company information</li>
272
  <li><strong>OTHER:</strong> All other types of websites (documentation, portfolios, etc.)</li>
273
  </ul>
274
  </div>
 
277
  process_btn.click(
278
  fn=process_single_url,
279
  inputs=[url_input],
280
+ outputs=[prediction_output, raw_prediction_output, scraped_output],
281
  show_progress=True
282
  )
283