dimoZ commited on
Commit
598cb89
Β·
verified Β·
1 Parent(s): cf0fdc1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -113
app.py CHANGED
@@ -2,128 +2,98 @@ import streamlit as st
2
  from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification, AutoModelForCausalLM
3
  import torch
4
 
5
- # -------------------------------
6
  # Page Configuration
7
- # -------------------------------
8
- st.set_page_config(
9
- page_title="AI Sentiment Essay Generator",
10
- page_icon="🧠",
11
- layout="wide"
12
- )
13
 
14
  st.markdown("""
15
- <style>
16
- body {
17
- background: radial-gradient(circle at top, #1f1f2e, #0f0f16);
18
- color: #f0f0f0;
19
- }
20
- .main {
21
- background-color: rgba(20, 20, 30, 0.8);
22
- padding: 30px;
23
- border-radius: 20px;
24
- box-shadow: 0px 0px 15px rgba(100,100,255,0.2);
25
- }
26
- textarea {
27
- border-radius: 10px !important;
28
- }
29
- </style>
30
  """, unsafe_allow_html=True)
31
 
32
- # -------------------------------
33
- # Title and Description
34
- # -------------------------------
35
  st.title("🧠 AI Sentiment Essay Generator")
36
- st.write("Enter a prompt β€” the AI will detect its sentiment (positive, negative, or neutral) "
37
- "and write an expressive paragraph aligned with that emotion πŸ’¬.")
38
 
39
- # -------------------------------
40
- # Load Models (Cached)
41
- # -------------------------------
42
  @st.cache_resource
43
- def load_sentiment_model():
44
- tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
45
- model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
46
- sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
47
- return sentiment_pipeline
48
 
49
- @st.cache_resource
50
- def load_generation_model():
51
- gen_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen1.5-0.5B-Chat")
52
- gen_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-0.5B-Chat")
53
- generator = pipeline("text-generation", model=gen_model, tokenizer=gen_tokenizer)
54
- return generator
55
-
56
- with st.spinner("Loading AI models... ⏳"):
57
- sentiment_analyzer = load_sentiment_model()
58
- text_generator = load_generation_model()
59
-
60
- # -------------------------------
61
- # Input Section
62
- # -------------------------------
63
- user_input = st.text_area("πŸ’¬ Enter your topic or prompt here:", height=120, placeholder="e.g., Technology and human connection...")
64
-
65
- generate_button = st.button("✨ Generate Essay")
66
-
67
- # -------------------------------
68
- # Main Logic
69
- # -------------------------------
70
- if generate_button and user_input.strip() != "":
71
- with st.spinner("Analyzing sentiment... 🧠"):
72
- sentiment_result = sentiment_analyzer(user_input)[0]
73
- label = sentiment_result["label"].capitalize()
74
- score = round(sentiment_result["score"] * 100, 2)
75
-
76
- # Sentiment-based UI styling
77
- if "Positive" in label:
78
- color = "#00C851"
79
- emoji = "😊"
80
- gradient = "linear-gradient(90deg, #00C851, #007E33)"
81
- elif "Negative" in label:
82
- color = "#ff4444"
83
- emoji = "😞"
84
- gradient = "linear-gradient(90deg, #ff4444, #CC0000)"
85
- else:
86
- color = "#33b5e5"
87
- emoji = "😐"
88
- gradient = "linear-gradient(90deg, #33b5e5, #0099CC)"
89
-
90
- st.markdown(f"""
91
- <div style='padding:15px;border-radius:12px;background:{gradient};text-align:center;'>
92
- <h3>{emoji} Detected Sentiment: <b>{label}</b> ({score}%)</h3>
93
- </div>
94
- """, unsafe_allow_html=True)
95
-
96
- # -------------------------------
97
- # Generate Sentiment-Aligned Text
98
- # -------------------------------
99
- prompt = f"Write a {label.lower()} and expressive paragraph about: {user_input}."
100
- with st.spinner(f"Generating a {label.lower()} essay... ✍️"):
101
- result = text_generator(prompt, max_length=200, do_sample=True, temperature=0.9)
102
- generated_text = result[0]["generated_text"]
103
-
104
- # -------------------------------
105
- # Display Output
106
- # -------------------------------
107
- st.subheader("πŸ“ AI-Generated Essay")
108
- st.markdown(
109
- f"""
110
- <div style='padding:20px;background-color:rgba(255,255,255,0.08);border-radius:15px;border-left:6px solid {color};'>
111
- <p style='font-size:1.1rem;line-height:1.6em;'>{generated_text}</p>
112
- </div>
113
- """, unsafe_allow_html=True
114
- )
115
 
116
- # -------------------------------
117
- # Sidebar Info
118
- # -------------------------------
119
- with st.sidebar:
120
- st.header("🧩 Summary")
121
- st.markdown(f"**Prompt:** {user_input}")
122
- st.markdown(f"**Sentiment:** {label} {emoji}")
123
- st.markdown(f"**Confidence:** {score}%")
124
- st.markdown("---")
125
- st.info("Tip: Try emotional prompts like *β€œlife after success”* or *β€œloneliness in a big city.”*")
126
 
127
- else:
128
- st.info("πŸ’‘ Enter your text above and click **Generate Essay** to begin!")
 
 
 
 
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification, AutoModelForCausalLM
3
  import torch
4
 
5
+ # ----------------------------------
6
  # Page Configuration
7
+ # ----------------------------------
8
+ st.set_page_config(page_title="AI Sentiment Essay Generator", page_icon="🧠", layout="wide")
 
 
 
 
9
 
10
  st.markdown("""
11
+ <style>
12
+ body {
13
+ background-color: #0e1117;
14
+ color: white;
15
+ }
16
+ .positive {background: linear-gradient(90deg, #3fc1c9, #4caf50); border-radius: 10px; padding: 1rem;}
17
+ .negative {background: linear-gradient(90deg, #f05454, #b33939); border-radius: 10px; padding: 1rem;}
18
+ .neutral {background: linear-gradient(90deg, #607d8b, #455a64); border-radius: 10px; padding: 1rem;}
19
+ </style>
 
 
 
 
 
 
20
  """, unsafe_allow_html=True)
21
 
 
 
 
22
  st.title("🧠 AI Sentiment Essay Generator")
23
+ st.caption("Analyze the emotion of your topic and let AI craft an expressive essay aligned with it 🎭")
 
24
 
25
+ # ----------------------------------
26
+ # Model Initialization (cached)
27
+ # ----------------------------------
28
  @st.cache_resource
29
+ def load_models():
30
+ sentiment_model_name = "cardiffnlp/twitter-roberta-base-sentiment-latest"
31
+ sentiment_analyzer = pipeline("sentiment-analysis", model=sentiment_model_name)
 
 
32
 
33
+ text_gen_model_name = "Qwen/Qwen1.5-1.8B"
34
+ tokenizer = AutoTokenizer.from_pretrained(text_gen_model_name)
35
+ text_model = AutoModelForCausalLM.from_pretrained(text_gen_model_name)
36
+ return sentiment_analyzer, tokenizer, text_model
37
+
38
+ sentiment_analyzer, tokenizer, text_model = load_models()
39
+
40
+ # ----------------------------------
41
+ # User Input
42
+ # ----------------------------------
43
+ user_prompt = st.text_area("πŸ’¬ Enter a topic or sentence:", placeholder="e.g., The future of Artificial Intelligence...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ generate_btn = st.button("✨ Generate Essay")
 
 
 
 
 
 
 
 
 
46
 
47
+ # ----------------------------------
48
+ # Processing
49
+ # ----------------------------------
50
+ if generate_btn and user_prompt.strip():
51
+ with st.spinner("Analyzing sentiment..."):
52
+ sentiment_result = sentiment_analyzer(user_prompt)[0]
53
 
54
+ label_map = {
55
+ "LABEL_0": "Negative",
56
+ "LABEL_1": "Neutral",
57
+ "LABEL_2": "Positive"
58
+ }
59
+
60
+ sentiment_label = label_map.get(sentiment_result["label"], sentiment_result["label"])
61
+ confidence = round(sentiment_result["score"] * 100, 2)
62
+
63
+ # Sentiment Display
64
+ sentiment_emoji = {"Positive": "😊", "Negative": "😠", "Neutral": "😐"}
65
+ sentiment_class = sentiment_label.lower()
66
+
67
+ st.markdown(f"<div class='{sentiment_class}'>", unsafe_allow_html=True)
68
+ st.markdown(
69
+ f"<h3 style='text-align:center;'>{sentiment_emoji.get(sentiment_label, '😐')} "
70
+ f"Detected Sentiment: <b>{sentiment_label}</b> ({confidence}%)</h3>",
71
+ unsafe_allow_html=True
72
+ )
73
+ st.markdown("</div>", unsafe_allow_html=True)
74
+
75
+ # ----------------------------------
76
+ # Generate Essay
77
+ # ----------------------------------
78
+ with st.spinner("Generating essay with AI..."):
79
+ gen_prompt = f"Write a {sentiment_label.lower()} and expressive essay about: {user_prompt}"
80
+
81
+ input_ids = tokenizer(gen_prompt, return_tensors="pt").input_ids
82
+ output_ids = text_model.generate(
83
+ input_ids,
84
+ max_new_tokens=250,
85
+ temperature=0.9,
86
+ top_p=0.95,
87
+ do_sample=True,
88
+ pad_token_id=tokenizer.eos_token_id
89
+ )
90
+ generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
91
+
92
+ st.markdown("### πŸ“ AI-Generated Essay")
93
+ st.write(generated_text)
94
+
95
+ st.markdown("---")
96
+ st.caption("✨ Powered by RoBERTa + Qwen | Streamlit Frontend")
97
+
98
+ elif generate_btn:
99
+ st.warning("⚠️ Please enter a topic or sentence first.")