Ginidu2003 commited on
Commit
945f42c
·
verified ·
1 Parent(s): 9706bb4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -0
app.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import torch
4
+ from transformers import pipeline
5
+ import nltk
6
+ from nltk.corpus import stopwords
7
+ from nltk.stem import WordNetLemmatizer
8
+ import re
9
+ import string
10
+
11
+ # ====================== PREPROCESSING ======================
12
+ nltk.download('stopwords', quiet=True)
13
+ nltk.download('wordnet', quiet=True)
14
+ nltk.download('punkt', quiet=True)
15
+
16
+ stop_words = set(stopwords.words('english'))
17
+ lemmatizer = WordNetLemmatizer()
18
+
19
+ def preprocess_text(text):
20
+ if not isinstance(text, str):
21
+ return ""
22
+ text = text.lower()
23
+ text = re.sub(f'[{string.punctuation}]', ' ', text)
24
+ text = re.sub(r'[^a-z\s]', ' ', text)
25
+ tokens = nltk.word_tokenize(text)
26
+ tokens = [word for word in tokens if word not in stop_words]
27
+ tokens = [lemmatizer.lemmatize(word) for word in tokens]
28
+ return ' '.join(tokens)
29
+
30
+ # ====================== LOAD YOUR FINE-TUNED MODEL ======================
31
+ model_name = "Ginidu2003/Distilbert-Base-News-classifier" # ← Change if your model name is different
32
+
33
+ @torch.no_grad()
34
+ def classify_csv(file):
35
+ try:
36
+ df = pd.read_csv(file)
37
+
38
+ if 'content' not in df.columns:
39
+ return "Error: CSV must have a column named 'content'", None
40
+
41
+ # Preprocess
42
+ df['clean_content'] = df['content'].apply(preprocess_text)
43
+
44
+ # Load classifier
45
+ classifier = pipeline("text-classification", model=model_name, device=-1)
46
+
47
+ # Predict
48
+ predictions = []
49
+ for text in df['clean_content']:
50
+ if not text.strip():
51
+ predictions.append("Unknown")
52
+ else:
53
+ result = classifier(text)[0]
54
+ predictions.append(result['label'])
55
+
56
+ df['class'] = predictions
57
+ df = df.drop(columns=['clean_content'], errors='ignore')
58
+
59
+ # Save output
60
+ output_file = "output.csv"
61
+ df.to_csv(output_file, index=False)
62
+
63
+ return f"✅ Success! Classified {len(df)} rows", output_file
64
+
65
+ except Exception as e:
66
+ return f"❌ Error: {str(e)}", None
67
+
68
+ # ====================== GRADIO INTERFACE ======================
69
+ with gr.Blocks(title="Daily Mirror News Classifier") as demo:
70
+ gr.Markdown("# 📰 Daily Mirror News Classifier")
71
+ gr.Markdown("### Classify news into Business, Opinion, Political Gossip, Sports, or World News")
72
+
73
+ with gr.Row():
74
+ file_input = gr.File(label="Upload CSV file", file_types=[".csv"])
75
+
76
+ classify_btn = gr.Button("🚀 Classify News", variant="primary")
77
+
78
+ output_text = gr.Textbox(label="Status")
79
+ output_file = gr.File(label="Download output.csv")
80
+
81
+ classify_btn.click(
82
+ fn=classify_csv,
83
+ inputs=file_input,
84
+ outputs=[output_text, output_file]
85
+ )
86
+
87
+ gr.Markdown("Built for Text Analytics Assignment - Section 02")
88
+
89
+ demo.launch()