LTH001 commited on
Commit
978e4d9
Β·
verified Β·
1 Parent(s): df77518

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -59
app.py CHANGED
@@ -1,71 +1,82 @@
1
  # app.py
2
  import streamlit as st
3
- from transformers import pipeline
4
- from PIL import Image
5
- import io
6
- from scipy.io.wavfile import write as write_wav
7
 
8
- def generate_image_caption(image):
9
- """Generates a caption for the given image"""
10
- img2caption = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
11
- result = img2caption(image)
12
- return result[0]['generated_text']
 
13
 
14
- def text2story(text):
15
- """Generates a children's story from text input"""
16
- story_prompt = f"Create a funny 100-word story for 8-year-olds about: {text}. Include: 1) A silly character 2) Magical object 3) Sound effects 4) Happy ending"
17
-
18
- pipe = pipeline("text-generation", model="pranavpsv/genre-story-generator-v2")
19
- story_text = pipe(
20
- story_prompt,
21
- max_new_tokens=200,
22
- temperature=0.9,
23
- top_k=50
24
- )[0]['generated_text']
25
- return story_text.split("Happy ending")[-1].strip()
26
 
27
- def story_to_speech(story_text):
28
- """Converts story text to audio using TTS"""
29
- tts_pipe = pipeline("text-to-speech", model="suno/bark-small")
30
- audio_output = tts_pipe(story_text[:400])
31
-
32
- # Convert to bytes using numpy directly
33
- audio_bytes = io.BytesIO()
34
- audio_np = (audio_output["audio"] * 32767).astype(np.int16)
35
- write_wav(audio_bytes, audio_output["sampling_rate"], audio_np)
36
- audio_bytes.seek(0)
37
-
38
- return audio_bytes
39
 
40
  def main():
41
- st.title("πŸ“– Image Story Generator with Audio")
42
- st.write("Upload an image to get a magical story read aloud!")
 
 
 
43
 
44
- uploaded_image = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
 
 
45
 
46
- if uploaded_image:
47
- image = Image.open(uploaded_image).convert("RGB")
48
- st.image(image, use_column_width=True)
49
-
50
- with st.spinner("✨ Analyzing image..."):
51
- caption = generate_image_caption(image)
52
-
53
- st.subheader("Image Understanding")
54
- st.write(caption)
55
-
56
- with st.spinner("πŸ“– Writing story..."):
57
- story = text2story(caption)
58
-
59
- st.subheader("Magical Story")
60
- st.write(story)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- if st.button("🎧 Read Story Aloud"):
63
- with st.spinner("πŸ”Š Generating audio..."):
64
- try:
65
- audio_bytes = story_to_speech(story)
66
- st.audio(audio_bytes, format="audio/wav")
67
- except Exception as e:
68
- st.error(f"Error generating audio: {str(e)}")
 
69
 
70
  if __name__ == "__main__":
71
- main()
 
1
  # app.py
2
  import streamlit as st
3
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
+ import torch
5
+ import numpy as np
 
6
 
7
+ # Page config
8
+ st.set_page_config(
9
+ page_title="Amazon Review Sentiment Analysis",
10
+ page_icon="πŸ“Š",
11
+ layout="wide"
12
+ )
13
 
14
+ @st.cache_resource
15
+ def load_model():
16
+ """Load the model and tokenizer."""
17
+ model_name = "LiYuan/amazon-review-sentiment-analysis"
18
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
19
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
20
+ return tokenizer, model
 
 
 
 
 
21
 
22
+ def predict_sentiment(text, tokenizer, model):
23
+ """Predict sentiment for given text."""
24
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
25
+ outputs = model(**inputs)
26
+ predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
27
+ return predictions.detach().numpy()[0]
 
 
 
 
 
 
28
 
29
  def main():
30
+ st.title("πŸ“Š Amazon Review Sentiment Analysis")
31
+ st.write("""
32
+ This application analyzes the sentiment of product reviews and predicts ratings (1-5 stars).
33
+ Enter your review text below to get started!
34
+ """)
35
 
36
+ # Load model
37
+ with st.spinner("Loading model..."):
38
+ tokenizer, model = load_model()
39
 
40
+ # Text input
41
+ text_input = st.text_area("Enter your review text:", height=150)
42
+
43
+ if st.button("Analyze Sentiment"):
44
+ if text_input.strip():
45
+ with st.spinner("Analyzing..."):
46
+ # Get prediction
47
+ predictions = predict_sentiment(text_input, tokenizer, model)
48
+ predicted_rating = np.argmax(predictions) + 1 # Add 1 since ratings are 1-5
49
+
50
+ # Display results
51
+ col1, col2 = st.columns(2)
52
+
53
+ with col1:
54
+ st.subheader("Predicted Rating")
55
+ st.markdown(f"<h1 style='text-align: center; color: #1f77b4;'>{'⭐' * predicted_rating}</h1>", unsafe_allow_html=True)
56
+
57
+ with col2:
58
+ st.subheader("Confidence Scores")
59
+ for i, score in enumerate(predictions, 1):
60
+ st.progress(float(score))
61
+ st.write(f"{i} Stars: {score:.2%}")
62
+ else:
63
+ st.warning("Please enter some text to analyze.")
64
+
65
+ # Additional information
66
+ with st.expander("About this Model"):
67
+ st.write("""
68
+ This application uses the LiYuan/amazon-review-sentiment-analysis model from HuggingFace.
69
+ The model is based on DistilBERT and was trained on a large dataset of Amazon product reviews.
70
+ It can predict ratings from 1 to 5 stars based on the review text.
71
 
72
+ Supported languages:
73
+ - English
74
+ - Dutch
75
+ - German
76
+ - French
77
+ - Spanish
78
+ - Italian
79
+ """)
80
 
81
  if __name__ == "__main__":
82
+ main()