frankai98 commited on
Commit
5782099
Β·
verified Β·
1 Parent(s): 646be0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -100
app.py CHANGED
@@ -1,112 +1,110 @@
1
- import os
2
- import nest_asyncio
3
- nest_asyncio.apply()
 
 
 
 
4
 
5
- import streamlit as st
6
- from transformers import pipeline
7
- from huggingface_hub import login
8
- from streamlit.components.v1 import html
 
9
 
10
- # Retrieve the token from environment variables
11
- hf_token = os.environ.get("HF_TOKEN")
12
- if not hf_token:
13
- st.error("Hugging Face token not found. Please set the HF_TOKEN environment variable.")
14
- st.stop()
15
 
16
- # Login with the token
17
- login(token=hf_token)
 
 
 
 
 
18
 
19
- # Initialize session state for timer and results
20
- if 'result' not in st.session_state:
21
- st.session_state.result = {}
22
- if 'timer_started' not in st.session_state:
23
- st.session_state.timer_started = False
24
- if 'timer_frozen' not in st.session_state:
25
- st.session_state.timer_frozen = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- # Timer component using HTML and JavaScript
28
- def timer():
29
- return """
30
- <div id="timer" style="font-size:16px;color:#666;margin-bottom:10px;">⏱️ Elapsed: 00:00</div>
31
- <script>
32
- (function() {
33
- var start = Date.now();
34
- var timerElement = document.getElementById('timer');
35
- localStorage.removeItem("freezeTimer");
36
- var interval = setInterval(function() {
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
- # Pass the token to the Gemma pipeline
61
- gemma_pipe = pipeline("text-generation", model="google/gemma-3-1b-it", use_auth_token=hf_token)
62
- return sentiment_pipe, gemma_pipe
63
 
64
- sentiment_pipe, gemma_pipe = load_models()
 
 
65
 
66
- # User input: a text area for the text to analyze
67
- user_input = st.text_area("Enter your text for sentiment analysis and report generation:")
 
 
 
 
68
 
69
- if st.button("Generate Report"):
70
- if not user_input.strip():
71
  st.error("Please enter some text!")
72
- else:
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
- status_text = st.empty()
78
- progress_bar = st.progress(0)
79
-
80
- try:
81
- # Stage 1: Sentiment Analysis
82
- status_text.markdown("**πŸ” Running sentiment analysis...**")
83
- progress_bar.progress(0)
84
- sentiment_result = sentiment_pipe(user_input)
85
- progress_bar.progress(50)
86
-
87
- # Stage 2: Generate Report using Gemma
88
- status_text.markdown("**πŸ“ Generating report with Gemma...**")
89
- prompt = f"""
90
- Generate a detailed report based on the following analysis.
91
-
92
- Original text:
93
- "{user_input}"
94
-
95
- Sentiment analysis result:
96
- {sentiment_result}
97
-
98
- Please provide a concise summary report explaining the sentiment and key insights.
99
- """
100
- report = gemma_pipe(prompt, max_length=200)
101
- progress_bar.progress(100)
102
- status_text.success("**βœ… Generation complete!**")
103
- html("<script>localStorage.setItem('freezeTimer', 'true');</script>", height=0)
104
- st.session_state.timer_frozen = True
105
-
106
- st.write("**Sentiment Analysis Result:**", sentiment_result)
107
- st.write("**Generated Report:**", report[0]['generated_text'])
108
-
109
- except Exception as e:
110
- html("<script>document.getElementById('timer').remove();</script>")
111
- status_text.error(f"**❌ Error:** {str(e)}")
112
  progress_bar.empty()
 
1
+ import os
2
+ import nest_asyncio
3
+ nest_asyncio.apply()
4
+ import streamlit as st
5
+ from transformers import pipeline
6
+ from huggingface_hub import login
7
+ from streamlit.components.v1 import html
8
 
9
+ # Retrieve the token from environment variables
10
+ hf_token = os.environ.get("HF_TOKEN")
11
+ if not hf_token:
12
+ st.error("Hugging Face token not found. Please set the HF_TOKEN environment variable.")
13
+ st.stop()
14
 
15
+ # Login with the token
16
+ login(token=hf_token)
 
 
 
17
 
18
+ # Initialize session state for timer and results
19
+ if 'result' not in st.session_state:
20
+ st.session_state.result = {}
21
+ if 'timer_started' not in st.session_state:
22
+ st.session_state.timer_started = False
23
+ if 'timer_frozen' not in st.session_state:
24
+ st.session_state.timer_frozen = False
25
 
26
+ # Timer component using HTML and JavaScript
27
+ def timer():
28
+ return """
29
+ <div id="timer" style="font-size:16px;color:#666;margin-bottom:10px;">⏱️ Elapsed: 00:00</div>
30
+ <script>
31
+ (function() {
32
+ var start = Date.now();
33
+ var timerElement = document.getElementById('timer');
34
+ localStorage.removeItem("freezeTimer");
35
+ var interval = setInterval(function() {
36
+ if(localStorage.getItem("freezeTimer") === "true"){
37
+ clearInterval(interval);
38
+ timerElement.style.color = '#00cc00';
39
+ return;
40
+ }
41
+ var elapsed = Date.now() - start;
42
+ var minutes = Math.floor(elapsed / 60000);
43
+ var seconds = Math.floor((elapsed % 60000) / 1000);
44
+ timerElement.innerHTML = '⏱️ Elapsed: ' +
45
+ (minutes < 10 ? '0' : '') + minutes + ':' +
46
+ (seconds < 10 ? '0' : '') + seconds;
47
+ }, 1000);
48
+ })();
49
+ </script>
50
+ """
51
 
52
+ st.set_page_config(page_title="Sentiment & Report Generator", page_icon="πŸ“")
53
+ st.header("Sentiment Analysis & Report Generation with Gemma")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ # Load models with caching to avoid reloading on every run
56
+ @st.cache_resource
57
+ def load_models():
58
+ sentiment_pipe = pipeline("text-classification", model="mixedbread-ai/mxbai-rerank-base-v1")
59
+ gemma_pipe = pipeline("text-generation", model="google/gemma-3-1b-it", use_auth_token=hf_token)
60
+ return sentiment_pipe, gemma_pipe
61
 
62
+ sentiment_pipe, gemma_pipe = load_models()
 
 
 
 
 
 
63
 
64
+ # Provide two options for input: text area or file upload
65
+ uploaded_file = st.file_uploader("Upload Review File (txt format)", type=["txt"])
66
+ user_input = st.text_area("Or, enter your text for sentiment analysis and report generation:")
67
 
68
+ # If a file is uploaded, override user_input with its contents
69
+ if uploaded_file is not None:
70
+ try:
71
+ user_input = uploaded_file.read().decode("utf-8")
72
+ except Exception as e:
73
+ st.error(f"Error reading file: {e}")
74
 
75
+ if st.button("Generate Report"):
76
+ if not user_input.strip():
77
  st.error("Please enter some text!")
78
+ else:
79
+ if not st.session_state.timer_started and not st.session_state.timer_frozen:
80
+ st.session_state.timer_started = True
81
+ html(timer(), height=50)
82
+ status_text = st.empty()
83
+ progress_bar = st.progress(0)
84
+ try:
85
+ # Stage 1: Sentiment Analysis
86
+ status_text.markdown("**πŸ” Running sentiment analysis...**")
87
+ progress_bar.progress(0)
88
+ sentiment_result = sentiment_pipe(user_input)
89
+ progress_bar.progress(50)
90
+ # Stage 2: Generate Report using Gemma
91
+ status_text.markdown("**πŸ“ Generating report with Gemma...**")
92
+ prompt = f"""
93
+ Generate a detailed report based on the following analysis.
94
+ Original text:
95
+ "{user_input}"
96
+ Sentiment analysis result:
97
+ {sentiment_result}
98
+ Please provide a concise summary report explaining the sentiment and key insights.
99
+ """
100
+ report = gemma_pipe(prompt, max_length=200)
101
+ progress_bar.progress(100)
102
+ status_text.success("**βœ… Generation complete!**")
103
+ html("<script>localStorage.setItem('freezeTimer', 'true');</script>", height=0)
104
+ st.session_state.timer_frozen = True
105
+ st.write("**Sentiment Analysis Result:**", sentiment_result)
106
+ st.write("**Generated Report:**", report[0]['generated_text'])
107
+ except Exception as e:
108
+ html("<script>document.getElementById('timer').remove();</script>")
109
+ status_text.error(f"**❌ Error:** {str(e)}")
 
 
 
 
 
 
 
 
110
  progress_bar.empty()