Keyurjotaniya007 commited on
Commit
ace0ac2
ยท
verified ยท
1 Parent(s): 4193902

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +70 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ๐Ÿ” Masked Word Predictor | CPU-only HF Space
2
+
3
+ import gradio as gr
4
+ import pandas as pd
5
+ from transformers import pipeline
6
+ from transformers.pipelines.base import PipelineException
7
+
8
+ # 1. Load the fill-mask pipeline once
9
+ fill_mask = pipeline("fill-mask", model="distilroberta-base", device=-1)
10
+
11
+ def predict_mask(sentence: str, top_k: int):
12
+ # 2. Get the actual mask token (e.g. "<mask>")
13
+ mask = fill_mask.tokenizer.mask_token
14
+
15
+ # 3. Allow users to type [MASK]
16
+ sentence = sentence.replace("[MASK]", mask)
17
+
18
+ # 4. Validate presence of mask
19
+ if mask not in sentence:
20
+ return pd.DataFrame(
21
+ [["Error: please include `[MASK]` in your sentence.", 0.0]],
22
+ columns=["Sequence", "Score"]
23
+ )
24
+
25
+ # 5. Run the pipeline safely
26
+ try:
27
+ preds = fill_mask(sentence, top_k=top_k)
28
+ except PipelineException as e:
29
+ return pd.DataFrame([[f"Error: {str(e)}", 0.0]],
30
+ columns=["Sequence", "Score"])
31
+
32
+ # 6. Build a DataFrame from list-of-lists
33
+ rows = [[p["sequence"], round(p["score"], 3)] for p in preds]
34
+ return pd.DataFrame(rows, columns=["Sequence", "Score"])
35
+
36
+ with gr.Blocks(title="๐Ÿ” Masked Word Predictor") as demo:
37
+ gr.Markdown(
38
+ "# ๐Ÿ” Masked Word Predictor\n"
39
+ "Enter a sentence with one `[MASK]` token and see the top-K completions."
40
+ )
41
+
42
+ with gr.Row():
43
+ sentence = gr.Textbox(
44
+ lines=2,
45
+ placeholder="e.g. The salonโ€™s new color treatment is [MASK].",
46
+ label="Input Sentence"
47
+ )
48
+ top_k = gr.Slider(
49
+ minimum=1, maximum=10, step=1, value=5,
50
+ label="Top K Predictions"
51
+ )
52
+
53
+ predict_btn = gr.Button("Predict ๐Ÿ”", variant="primary")
54
+
55
+ results_df = gr.Dataframe(
56
+ headers=["Sequence", "Score"],
57
+ datatype=["str", "number"],
58
+ wrap=True,
59
+ interactive=False,
60
+ label="Predictions"
61
+ )
62
+
63
+ predict_btn.click(
64
+ fn=predict_mask,
65
+ inputs=[sentence, top_k],
66
+ outputs=results_df
67
+ )
68
+
69
+ if __name__ == "__main__":
70
+ demo.launch(server_name="0.0.0.0")
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio==5.31.0
2
+ transformers>=4.30.0
3
+ torch>=2.0.0