frankai98 commited on
Commit
8b9bf01
Β·
verified Β·
1 Parent(s): 2382fa5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -20
app.py CHANGED
@@ -1,35 +1,120 @@
 
 
 
 
 
 
1
  from transformers import pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- # Step 1: Define the sentiment analysis pipeline.
4
- # Here, we use a text classification model.
5
- sentiment_pipe = pipeline("text-classification", model="mixedbread-ai/mxbai-rerank-base-v1")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # Step 2: Define the text generation pipeline with Gemma.
8
- gemma_pipe = pipeline("text-generation", model="google/gemma-3-1b-it")
9
 
10
- # Example input text that we want to analyze.
11
- text = "I love this new product. It has exceeded my expectations and I feel very happy about it."
 
 
 
 
12
 
13
- # Perform sentiment analysis on the text.
14
- sentiment_result = sentiment_pipe(text)
15
- print("Sentiment Analysis Result:")
16
- print(sentiment_result)
17
 
18
- # Prepare a prompt that includes the original text and the sentiment result.
19
- # The prompt instructs the Gemma model to generate a detailed summary report.
20
- prompt = f"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  Generate a detailed report based on the following analysis.
22
 
23
  Original text:
24
- "{text}"
25
 
26
  Sentiment analysis result:
27
  {sentiment_result}
28
 
29
  Please provide a concise summary report explaining the sentiment and key insights.
30
  """
31
-
32
- # Use the Gemma pipeline to generate the summary report.
33
- report = gemma_pipe(prompt, max_length=200)
34
- print("\nGenerated Report:")
35
- print(report[0]['generated_text'])
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import nest_asyncio
2
+ nest_asyncio.apply()
3
+
4
+ import streamlit as st
5
+ import asyncio
6
+ import subprocess
7
  from transformers import pipeline
8
+ from streamlit.components.v1 import html
9
+
10
+ # -----------------------------------------------------------
11
+ # Hugging Face CLI Login
12
+ # This will prompt you in the terminal for your Hugging Face token.
13
+ # Ensure you have your token ready.
14
+ subprocess.run(["huggingface-cli", "login"], shell=True)
15
+ # -----------------------------------------------------------
16
+
17
+ # Initialize session state for timer and results
18
+ if 'result' not in st.session_state:
19
+ st.session_state.result = {}
20
+ if 'timer_started' not in st.session_state:
21
+ st.session_state.timer_started = False
22
+ if 'timer_frozen' not in st.session_state:
23
+ st.session_state.timer_frozen = False
24
 
25
+ # Timer component using HTML and JavaScript
26
+ def timer():
27
+ return """
28
+ <div id="timer" style="font-size:16px;color:#666;margin-bottom:10px;">⏱️ Elapsed: 00:00</div>
29
+ <script>
30
+ (function() {
31
+ var start = Date.now();
32
+ var timerElement = document.getElementById('timer');
33
+ // Remove any existing freeze flag
34
+ localStorage.removeItem("freezeTimer");
35
+ var interval = setInterval(function() {
36
+ // If freeze flag is set, stop the timer
37
+ if(localStorage.getItem("freezeTimer") === "true"){
38
+ clearInterval(interval);
39
+ timerElement.style.color = '#00cc00';
40
+ return;
41
+ }
42
+ var elapsed = Date.now() - start;
43
+ var minutes = Math.floor(elapsed / 60000);
44
+ var seconds = Math.floor((elapsed % 60000) / 1000);
45
+ timerElement.innerHTML = '⏱️ Elapsed: ' +
46
+ (minutes < 10 ? '0' : '') + minutes + ':' +
47
+ (seconds < 10 ? '0' : '') + seconds;
48
+ }, 1000);
49
+ })();
50
+ </script>
51
+ """
52
 
53
+ st.set_page_config(page_title="Sentiment & Report Generator", page_icon="πŸ“")
54
+ st.header("Sentiment Analysis & Report Generation with Gemma")
55
 
56
+ # Load models with caching to avoid reloading on every run
57
+ @st.cache_resource
58
+ def load_models():
59
+ sentiment_pipe = pipeline("text-classification", model="mixedbread-ai/mxbai-rerank-base-v1")
60
+ gemma_pipe = pipeline("text-generation", model="google/gemma-3-1b-it")
61
+ return sentiment_pipe, gemma_pipe
62
 
63
+ sentiment_pipe, gemma_pipe = load_models()
 
 
 
64
 
65
+ # User input: a text area for the text to analyze
66
+ user_input = st.text_area("Enter your text for sentiment analysis and report generation:")
67
+
68
+ if st.button("Generate Report"):
69
+ if not user_input.strip():
70
+ st.error("Please enter some text!")
71
+ else:
72
+ # Start the timer if not already started
73
+ if not st.session_state.timer_started and not st.session_state.timer_frozen:
74
+ st.session_state.timer_started = True
75
+ html(timer(), height=50)
76
+
77
+ # Initialize status message and progress bar
78
+ status_text = st.empty()
79
+ progress_bar = st.progress(0)
80
+
81
+ try:
82
+ # ---------------------------
83
+ # Stage 1: Sentiment Analysis
84
+ status_text.markdown("**πŸ” Running sentiment analysis...**")
85
+ progress_bar.progress(0)
86
+ sentiment_result = sentiment_pipe(user_input)
87
+ progress_bar.progress(50)
88
+
89
+ # ---------------------------
90
+ # Stage 2: Generate Report using Gemma
91
+ status_text.markdown("**πŸ“ Generating report with Gemma...**")
92
+ # Build a prompt that includes the original text and the sentiment analysis result.
93
+ prompt = f"""
94
  Generate a detailed report based on the following analysis.
95
 
96
  Original text:
97
+ "{user_input}"
98
 
99
  Sentiment analysis result:
100
  {sentiment_result}
101
 
102
  Please provide a concise summary report explaining the sentiment and key insights.
103
  """
104
+ report = gemma_pipe(prompt, max_length=200)
105
+ progress_bar.progress(100)
106
+ status_text.success("**βœ… Generation complete!**")
107
+
108
+ # Freeze the timer immediately upon completion.
109
+ html("<script>localStorage.setItem('freezeTimer', 'true');</script>", height=0)
110
+ st.session_state.timer_frozen = True
111
+
112
+ # Display the results
113
+ st.write("**Sentiment Analysis Result:**", sentiment_result)
114
+ st.write("**Generated Report:**", report[0]['generated_text'])
115
+
116
+ except Exception as e:
117
+ # Remove timer element if an error occurs
118
+ html("<script>document.getElementById('timer').remove();</script>")
119
+ status_text.error(f"**❌ Error:** {str(e)}")
120
+ progress_bar.empty()