File size: 7,817 Bytes
f492c51
 
 
 
 
 
cb43061
d3e21b9
f492c51
 
 
 
cb43061
f492c51
cb43061
f492c51
02a1163
 
 
 
 
 
 
cb43061
02a1163
 
cb43061
02a1163
 
 
f492c51
02a1163
 
f492c51
cb43061
 
 
 
 
 
 
 
 
 
 
 
 
 
f492c51
cb43061
02a1163
cb43061
 
 
 
 
 
 
 
 
 
 
02a1163
 
 
f492c51
02a1163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f492c51
1285454
 
 
 
 
 
 
 
 
f492c51
1285454
 
 
 
 
 
 
 
 
 
 
 
f492c51
1285454
 
f492c51
1285454
 
f492c51
1285454
 
 
 
 
 
cb43061
1285454
cb43061
1285454
cb43061
1285454
 
 
 
 
 
 
 
 
 
f492c51
1285454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb43061
1285454
 
 
 
cb43061
1285454
 
 
 
cb43061
1285454
 
f492c51
1285454
 
 
 
 
 
 
f492c51
1285454
 
 
 
 
 
 
 
f492c51
1285454
 
f492c51
1285454
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import streamlit as st
import random
import pandas as pd
import requests
from io import BytesIO
from PIL import Image
from transformers import pipeline

# Define maximum dimensions for the fortune image (in pixels)
MAX_SIZE = (400, 400)

# Set page configuration
st.set_page_config(page_title="Fortuen Stick Enquiry", layout="wide")

st.title("Fortuen Stick Enquiry")

# Initialize session state variables
if "submitted_text" not in st.session_state:
    st.session_state.submitted_text = False
if "fortune_number" not in st.session_state:
    st.session_state.fortune_number = None
if "fortune_row" not in st.session_state:
    st.session_state.fortune_row = None

if "fortune_data" not in st.session_state:
    try:
        st.session_state.fortune_data = pd.read_csv("detail.csv")
    except Exception as e:
        st.error(f"Error loading CSV: {e}")
        st.session_state.fortune_data = None

if "stick_clicked" not in st.session_state:
    st.session_state.stick_clicked = False

# Update the check functions to use the "question" parameter properly.
def check_sentence_is_english_model(question):
    pipe = pipeline("text-classification", model="papluca/xlm-roberta-base-language-detection")
    # If the model predicts the label "en", we consider it English.
    if pipe(question)[0]['label'] == 'en':
        return True
    return False

def check_sentence_is_question_model(question):
    pipe = pipeline("text-classification", model="shahrukhx01/question-vs-statement-classifier")
    # If the model predicts "LABEL_1", we consider it a question.
    if pipe(question)[0]['label'] == 'LABEL_1':
        return True
    return False

# Callback function for the submit button (no parameters now)
def submit_text_callback():
    # Get the user input from session state
    question = st.session_state.get("user_sentence", "")
    
    if not check_sentence_is_english_model(question):
        st.error("Please enter in English")
        return

    if not check_sentence_is_question_model(question):
        st.error("This is not a question. Please enter another question")
        return

    st.session_state.submitted_text = True
    # Randomly generate a number from 1 to 100
    st.session_state.fortune_number = random.randint(1, 100)
    
    # Look up the row in the CSV where CNumber matches the generated fortune number.
    df = st.session_state.fortune_data
    if df is not None:
        matching_row = df[df['CNumber'] == st.session_state.fortune_number]
        if not matching_row.empty:
            row = matching_row.iloc[0]
            st.session_state.fortune_row = {
                "Header": row.get("Header", "N/A"),
                "Luck": row.get("Luck", "N/A"),
                "Description": row.get("Description", "No description available."),
                "Detail": row.get("Detail", "No detail available."),
                "HeaderLink": row.get("link", None)  # URL to the image
            }
        else:
            st.session_state.fortune_row = {
                "Header": "N/A",
                "Luck": "N/A",
                "Description": "No description available.",
                "Detail": "No detail available.",
                "HeaderLink": None
            }

# Function to load and resize local images using Pillow
def load_and_resize_image(path, max_size=MAX_SIZE):
    try:
        img = Image.open(path)
        img.thumbnail(max_size, Image.Resampling.LANCZOS)
        return img
    except Exception as e:
        st.error(f"Error loading image: {e}")
        return None

# Function to download image from URL and resize it
def download_and_resize_image(url, max_size=MAX_SIZE):
    try:
        response = requests.get(url)
        response.raise_for_status()
        image_bytes = BytesIO(response.content)
        img = Image.open(image_bytes)
        img.thumbnail(max_size, Image.Resampling.LANCZOS)
        return img
    except Exception as e:
        st.error(f"Error loading image from URL: {e}")
        return None

def stick_enquiry_callback():
    st.session_state.stick_clicked = True

# Main layout: Left (input) and Right (fortune display)
left_col, _, right_col = st.columns([3, 1, 5])

# ---- Left Column ----
with left_col:
    left_top = st.container()
    left_bottom = st.container()
    # Top container: Input area and submit button
    with left_top:
        # Text area for user input (saved into session_state with key "user_sentence")
        user_sentence = st.text_area("Enter your question in English", key="user_sentence", height=150)
        # The callback no longer requires a parameter; it accesses st.session_state directly.
        st.button("submit", key="submit_button", on_click=submit_text_callback)
    # Left Bottom: Centered "Cfu Explain" button
    if st.session_state.submitted_text:
        with left_bottom:
            # Add vertical spacing to approximately center the button vertically
            for _ in range(5):
                st.write("")
            col1, col2, col3 = st.columns(3)
            with col2:
                st.button("Cfu Explain", key="stick_button", on_click=stick_enquiry_callback)
            if st.session_state.stick_clicked:
                st.text_area(' ', value="Here are the stick enquiry words...", height=300, disabled=True)

# ---- Right Column ----
with right_col:
    # Top container: Fortune image area
    with st.container():
        col_left, col_center, col_right = st.columns([1, 2, 1])
        with col_center:
            if st.session_state.submitted_text and st.session_state.fortune_row:
                header_link = st.session_state.fortune_row.get("HeaderLink")
                if header_link:
                    # Download the image from the URL
                    img_from_url = download_and_resize_image(header_link)
                    if img_from_url:
                        st.image(img_from_url, use_container_width=False)
                    else:
                        # Fallback: display a default image if download fails
                        img = load_and_resize_image("error.png")
                        if img:
                            st.image(img, use_container_width=False)
                else:
                    # Fallback: display a default image if no header link is provided
                    img = load_and_resize_image("error.png")
                    if img:
                        st.image(img, use_container_width=False)
            else:
                # Before submit, show the default image
                img = load_and_resize_image("fortune.png")
                if img:
                    st.image(img, caption="Your Fortune", use_container_width=False)
    
    # Bottom container: Display fortune details using text areas
    with st.container():
        if st.session_state.fortune_row:
            header_text = st.session_state.fortune_row.get("Header", "N/A")
            luck_text = st.session_state.fortune_row.get("Luck", "N/A")
            description_text = st.session_state.fortune_row.get("Description", "No description available.")
            detail_text = st.session_state.fortune_row.get("Detail", "No detail available.")
            
            # Create a summary with larger text using HTML styling
            summary = f"""
            <div style="font-size: 28px; font-weight: bold;">
                Fortune stick number: {st.session_state.fortune_number}<br>
                Luck: {luck_text}
            </div>
            """
            st.markdown(summary, unsafe_allow_html=True)
            
            # Second text area: Description
            st.text_area("Description", value=description_text, height=150, disabled=True)
            
            # Third text area: Detail
            st.text_area("Detail", value=detail_text, height=150, disabled=True)