File size: 5,946 Bytes
3b27d22
 
 
 
faa4567
3b27d22
 
 
faa4567
3b27d22
 
faa4567
 
ce2e0aa
 
 
 
 
 
 
 
3b27d22
ce2e0aa
 
 
 
 
 
 
3b27d22
 
57d56b2
faa4567
a83b821
b5adeaf
57d56b2
 
b5adeaf
faa4567
 
 
 
3b27d22
57d56b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b27d22
faa4567
57d56b2
 
3b27d22
 
 
57d56b2
 
faa4567
57d56b2
 
 
faa4567
 
 
 
 
 
3b27d22
faa4567
 
 
 
0429e40
 
 
 
57d56b2
 
 
 
 
 
 
 
 
 
 
 
faa4567
 
 
 
3b27d22
faa4567
3b27d22
faa4567
 
3b27d22
 
faa4567
3b27d22
faa4567
 
d51e5d9
 
 
 
 
 
 
faa4567
 
 
 
 
 
 
 
3b27d22
 
faa4567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b27d22
 
faa4567
3b27d22
 
faa4567
3b27d22
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
import os
import streamlit as st
from PIL import Image
import pyperclip
import CaptionGenerator
import app_utils as utils

# Define Streamlit configurations
st.set_page_config(page_title="Instamuse", page_icon=":camera:", layout='wide')

# Initialize the caption generator
caption_generator = CaptionGenerator.CaptionGenerator()

# Define custom CSS for background color
page_bg = '''
<style>
body {
    background-color: #21011e; /* Dark Purple */
}
</style>
'''


# # Sidebar configuration
# with st.sidebar:
#     st.image(os.path.join('images', 'insta.png'), width=300)
#     st.title("Welcome to InstaMuse!")
#     st.subheader("Turn your snapshots into social media sensations.")
#     st.write("Start turning heads with your posts. Use InstaMuse now and watch your likes soar!")

# Main page content
st.markdown('## InstaMuse Photo Caption Generator')
st.write("""### Upload your photo below and spark some caption magic! ଘ(ΰ©­ΛŠα΅•Λ‹)ΰ©­* ΰ©ˆβœ©β€§β‚Š""")

st.write(
f'**Notice**: *Due to model load time, it may take a moment to load the application. This only occurs once.* \n*Subsequent uploads will be faster.*'
)

# Load the model for image description
with st.spinner('Loading Application, this make take a minute :hourglass_flowing_sand:'):
    # Load the model for image captioning
    model, processor = utils.init_model()


def clear_cache():
    """
    Function to clear the session state cache.
    """
    if 'file' in st.session_state:
        del st.session_state['file']
    if 'captions' in st.session_state:
        del st.session_state['captions']
    if 'caption_list' in st.session_state:
        del st.session_state['caption_list']
    if 'img_description' in st.session_state:
        del st.session_state['img_description']
    st.rerun()

# Upload image file and process image
uploaded_file = st.file_uploader(
    "Upload your image here:", type=["jpg", "png"],
    help="Only jpg and png images are supported"
)


if uploaded_file:
    if 'file' not in st.session_state:
        st.session_state['file'] = uploaded_file
        image = Image.open(uploaded_file)
        image.thumbnail((400, 400), Image.Resampling.LANCZOS)
        st.session_state['image'] = image

    col1, col2 = st.columns(2)
    with st.container():
        with col1:
            st.markdown("## πŸ“Έ Your Image:")
            st.image(st.session_state['image'], caption='Uploaded Image', use_column_width=True)

        with col2:
            with st.spinner(r'#### :sparkles: :sparkles: Generating... please wait :hourglass_flowing_sand:'):
                if 'captions' not in st.session_state:
                    desc = caption_generator.image_2_text(image, model, processor)
                    captions, caption_list, img_description = caption_generator.text_2_caption(desc)
                    st.session_state['captions'] = captions
                    st.session_state['caption_list'] = caption_list
                    st.session_state['img_description'] = img_description
                    st.markdown("## πŸ“ Generated Captions:")
                    for caption in st.session_state['caption_list']:
                        if caption.strip() != "":
                            st.info(f"##### {caption}")

                elif st.session_state['file'] != uploaded_file:
                    clear_cache()
                    desc = caption_generator.image_2_text(image, model, processor)
                    captions, caption_list, img_description = caption_generator.text_2_caption(desc)
                    st.session_state['captions'] = captions
                    st.session_state['caption_list'] = caption_list
                    st.session_state['img_description'] = img_description
                    st.markdown("## πŸ“ Generated Captions:")
                    for caption in st.session_state['caption_list']:
                        if caption.strip() != "":
                            st.info(f"##### {caption}")

                else:
                    st.markdown("## πŸ“ Generated Captions:")
                    for caption in st.session_state['caption_list']:
                        if caption.strip() != "":
                            st.info(f"##### {caption}")

        st.markdown("---")

        col3, col4, col5, col6 = st.columns(4)
        if col3.button("πŸ“‹ Copy Captions"):
            try:
                pyperclip.copy(st.session_state['captions'])
                st.success("Captions copied to clipboard!")
            except Exception as e:
                st.error('Unable to copy to clipboard on this system ):')
            
                

        if col4.button("πŸ”„ Regenerate Captions"):
            # Forcefully clear file to trigger reprocessing
            if 'file' in st.session_state:
                del st.session_state['file']
                del st.session_state['captions']
                del st.session_state['caption_list']
                del st.session_state['img_description']
                st.rerun()

        if col5.button("✨ More Hashtags"):
            if 'img_description' in st.session_state:
                with st.spinner('Generating hashtags...'):
                    try:
                        hashtags = caption_generator.caption_2_hashtag(st.session_state['img_description'])
                        st.write("### Generated Hashtags:")
                        st.write(f"**{hashtags}**")
                    except Exception as e:
                        st.error(f"Error generating hashtags: {e}")

        if col6.button(":x: Report Issue"):
            st.write("You are beta testing this app. Please report any issues to the developer. Thank you")


st.markdown("---")

with st.expander("Need help?"):
    st.write("Please contact us by [email](mailto:[email protected])")  # Correct the email link

st.markdown("---")

st.caption("Thank you for using InstaMuse! Feel free to contact us for any suggestions or issues.")