minemaster01 commited on
Commit
49b1ef8
·
verified ·
1 Parent(s): 54967e6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -0
app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import datetime
3
+ import torch
4
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
5
+ from datasets import load_dataset, Dataset, DatasetDict
6
+ import huggingface_hub
7
+ import pandas as pd
8
+
9
+ # CONFIG
10
+ MODEL_NAME = "distilbert-base-uncased-finetuned-sst-2-english" # replace with your own
11
+ HF_DATASET_REPO = "your-username/your-logging-dataset" # create on HF Hub
12
+ HF_TOKEN = "hf_..." # your Hugging Face token with write access
13
+
14
+ # Load model + tokenizer
15
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
16
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
17
+
18
+ # Setup dataset pushing
19
+ huggingface_hub.login(token=HF_TOKEN)
20
+
21
+ # Store session logs
22
+ log_entries = []
23
+
24
+ def infer_and_log(text_input):
25
+ inputs = tokenizer(text_input, return_tensors="pt", truncation=True)
26
+ with torch.no_grad():
27
+ outputs = model(**inputs)
28
+ logits = outputs.logits.tolist()
29
+ predicted = torch.argmax(outputs.logits, dim=-1).item()
30
+ output_label = model.config.id2label[predicted]
31
+
32
+ # Create log entry
33
+ log_entries.append({
34
+ "timestamp": datetime.datetime.now().isoformat(),
35
+ "input": text_input,
36
+ "logits": logits,
37
+ })
38
+
39
+ return output_label
40
+
41
+ def clear_fields():
42
+ return "", ""
43
+
44
+ def save_to_hf():
45
+ if not log_entries:
46
+ return "Nothing to save."
47
+
48
+ dataset = Dataset.from_pandas(pd.DataFrame(log_entries))
49
+ dataset.push_to_hub(HF_DATASET_REPO)
50
+ log_entries.clear()
51
+ return "Data saved to Hugging Face!"
52
+
53
+ with gr.Blocks() as demo:
54
+ gr.Markdown("### 🔤 Text Classification Demo")
55
+
56
+ with gr.Row():
57
+ input_box = gr.Textbox(label="Input Text", lines=5, interactive=True)
58
+ output_box = gr.Textbox(label="Predicted Label", lines=5)
59
+
60
+ with gr.Row():
61
+ submit_btn = gr.Button("Submit")
62
+ clear_btn = gr.Button("Clear")
63
+
64
+ status_box = gr.Textbox(label="Status", interactive=False)
65
+
66
+ submit_btn.click(fn=infer_and_log, inputs=input_box, outputs=output_box)
67
+ clear_btn.click(fn=clear_fields, outputs=[input_box, output_box])
68
+
69
+ gr.Button("Save Logs to Hub").click(fn=save_to_hf, outputs=status_box)
70
+
71
+ if __name__ == "__main__":
72
+ demo.launch()