rviana commited on
Commit
c61aa36
1 Parent(s): eed2c8b

Fix input and thread with gradio.

Browse files
Files changed (1) hide show
  1. app.py +21 -27
app.py CHANGED
@@ -1,32 +1,16 @@
1
  import gradio as gr
 
2
  import streamlit as st
3
  import socket
 
4
 
5
- try:
6
- from transformers import pipeline
7
- except ImportError as e:
8
- st.error(f"ImportError: {e}")
9
- st.stop()
10
- except Exception as e:
11
- st.error(f"Unexpected error: {e}")
12
- st.stop()
13
-
14
- # Specify the model name explicitly to avoid warnings
15
- model_name = "distilbert-base-uncased-finetuned-sst-2-english"
16
-
17
- try:
18
- classifier = pipeline('sentiment-analysis', model=model_name)
19
- except Exception as e:
20
- st.error(f"Error loading pipeline: {e}")
21
- st.stop()
22
 
23
  # Function to classify sentiment
24
  def classify_text(text):
25
- try:
26
- result = classifier(text)[0]
27
- return f"{result['label']} with score {result['score']}"
28
- except Exception as e:
29
- return f"Error classifying text: {e}"
30
 
31
  # Function to find an available port
32
  def find_free_port():
@@ -34,13 +18,23 @@ def find_free_port():
34
  s.bind(('', 0))
35
  return s.getsockname()[1]
36
 
37
- # Find an available port
38
- port = find_free_port()
 
 
39
 
40
- # Launch the Gradio interface on the dynamically found port
41
- iface = gr.Interface(fn=classify_text, inputs="text", outputs="text")
42
- iface.launch(server_port=port)
43
 
44
  # Streamlit code
45
  st.title('IMDb Sentiment Analysis')
46
  st.write('This project performs sentiment analysis on IMDb movie reviews using Streamlit.')
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
  import streamlit as st
4
  import socket
5
+ import threading
6
 
7
+ # Load the pre-trained sentiment-analysis pipeline
8
+ classifier = pipeline('sentiment-analysis')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  # Function to classify sentiment
11
  def classify_text(text):
12
+ result = classifier(text)[0]
13
+ return f"{result['label']} with score {result['score']}"
 
 
 
14
 
15
  # Function to find an available port
16
  def find_free_port():
 
18
  s.bind(('', 0))
19
  return s.getsockname()[1]
20
 
21
+ # Function to run Gradio in a separate thread
22
+ def run_gradio():
23
+ iface = gr.Interface(fn=classify_text, inputs="text", outputs="text")
24
+ iface.launch(server_port=find_free_port())
25
 
26
+ # Start Gradio in a separate thread
27
+ threading.Thread(target=run_gradio).start()
 
28
 
29
  # Streamlit code
30
  st.title('IMDb Sentiment Analysis')
31
  st.write('This project performs sentiment analysis on IMDb movie reviews using Streamlit.')
32
+
33
+ st.text_input("Enter text for sentiment analysis", key="input_text")
34
+ if st.button("Classify"):
35
+ text = st.session_state.input_text
36
+ if text:
37
+ result = classify_text(text)
38
+ st.write(result)
39
+ else:
40
+ st.write("Please enter text for classification.")