dimoZ commited on
Commit
59c8aff
·
verified ·
1 Parent(s): ed27b85

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -0
app.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
+