deee007 commited on
Commit
a539582
·
verified ·
1 Parent(s): c37c998

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -0
app.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import streamlit as st
3
+ from transformers import pipeline
4
+
5
+ # Page configuration
6
+ st.set_page_config(
7
+ page_title="AI Text Generator",
8
+ page_icon="🤖",
9
+ layout="centered"
10
+ )
11
+
12
+ # Mandatory title: Name and Student ID
13
+ st.title("Dawar Shariq | Student ID: B04-0923-000022")
14
+
15
+ st.header("AI Text Generator")
16
+ st.write(
17
+ "Enter a prompt and let the AI generate a continuation "
18
+ "using a pretrained Hugging Face model."
19
+ )
20
+
21
+ # Load and cache the model so it is not reloaded on every interaction
22
+ MODEL_NAME = "distilgpt2"
23
+
24
+ @st.cache_resource
25
+ def load_model():
26
+ return pipeline(
27
+ "text-generation",
28
+ model=MODEL_NAME
29
+ )
30
+
31
+ # Load the model
32
+ with st.spinner("Loading AI model..."):
33
+ generator = load_model()
34
+
35
+ st.success(f"Model loaded: {MODEL_NAME}")
36
+
37
+ # Input widget
38
+ prompt = st.text_area(
39
+ "Enter your starting text:",
40
+ placeholder="Artificial intelligence can help people...",
41
+ height=120
42
+ )
43
+
44
+ # Required feature: control maximum generated tokens
45
+ max_new_tokens = st.slider(
46
+ "Maximum new tokens",
47
+ min_value=10,
48
+ max_value=200,
49
+ value=50,
50
+ step=10
51
+ )
52
+
53
+ # Button and model call
54
+ if st.button("Generate Text", type="primary"):
55
+ if prompt.strip():
56
+ with st.spinner("Generating text..."):
57
+ result = generator(
58
+ prompt,
59
+ max_new_tokens=max_new_tokens,
60
+ num_return_sequences=1,
61
+ do_sample=True,
62
+ temperature=0.8,
63
+ pad_token_id=generator.tokenizer.eos_token_id
64
+ )
65
+
66
+ # Display only the generated continuation
67
+ full_text = result[0]["generated_text"]
68
+ continuation = full_text[len(prompt):]
69
+
70
+ st.subheader("Generated Continuation")
71
+ if continuation.strip():
72
+ st.write(continuation)
73
+ else:
74
+ st.write(full_text)
75
+
76
+ else:
77
+ st.warning("Please enter a prompt before generating text.")
78
+
79
+ # Model information
80
+ with st.expander("About this application"):
81
+ st.write("Model: distilgpt2")
82
+ st.write("Pipeline task: text-generation")
83
+ st.write("Framework: Hugging Face Transformers")
84
+ st.write("Interface: Streamlit")