Spaces:
Sleeping
Sleeping
File size: 7,676 Bytes
aa2aac7 1cfa2c8 aa2aac7 cd40ca4 aa2aac7 |
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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 |
import google.generativeai as genai
import streamlit as st
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("GOOGLE_API_KEY")
MODEL_NAME = "gemini-2.0-flash"
SAFETY_SETTINGS = [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
]
def initialize_gemini():
try:
model = genai.GenerativeModel(MODEL_NAME, safety_settings=SAFETY_SETTINGS)
return model
except Exception as e:
st.error(f"Error initializing Gemini model: {e}")
return None
def get_gemini_response(model, prompt,
output_format=None, tone=None, length=None, num_responses=1, creative_mode=False, fact_checking=False, chat=None):
constructed_prompt = prompt
if output_format:
constructed_prompt += f" Generate this in the format of a {output_format}."
if tone:
constructed_prompt += f" Use a {tone} tone."
if length:
constructed_prompt += f" The generated text should be approximately {length} words long."
if creative_mode:
constructed_prompt += " Be creative."
if fact_checking:
constructed_prompt += " Please ensure factual accuracy."
try:
if chat:
response = chat.send_message(constructed_prompt)
else:
response = model.generate_content(constructed_prompt, generation_config=genai.types.GenerationConfig(candidate_count=num_responses))
return response.text if response else None
except Exception as e:
st.error(f"Error generating response: {e}")
return None
custom_css = """
<style>
.user-message {
background-color: #b49577;
border-radius: 10px;
padding: 25px 30px;
margin-bottom: 3px;
text-align: right;
width: fit-content;
margin-left: auto;
word-break: break-word;
}
.gemini-message {
background-color: #FFFFFF;
border-radius: 10px;
padding: 25px 30px;
margin-bottom: 3px;
text-align: left;
width: fit-content;
margin-right: auto;
word-break: break-word;
font-size: 16px;
font-family: sans-serif;
line-height: 1.6;
}
.message-container {
display: flex;
flex-direction: column;
margin-bottom: 10px;
}
.stChatMessage {
padding: 0px;
border: none;
background-color: transparent;
}
/* CSS for the loading dots */
.loader {
font-size: 2em; /* Adjust size as needed */
color: #3498db; /* Loading dots color */
}
.loader:after {
content: ' .';
animation: dots 1s steps(5, end) infinite;
}
@keyframes dots {
0%, 20% {
content: ' .';
}
40% {
content: ' ..';
}
60%, 80% {
content: ' ...';
}
100% {
content: ' .';
}
}
/* Styles for input boxes */
div.stTextArea > div > div > textarea {
background-color: #f0f2f6 !important; /* Light gray background */
border-radius: 5px;
padding: 8px;
color: black; /* Ensuring text is readable */
}
div.stSelectbox > label {
color: black;
}
div.stSelectbox > div > button {
background-color: #f0f2f6 !important;
color: black;
border-radius: 5px;
}
div.stNumberInput > label {
color: black;
}
div.stNumberInput > div > div input {
background-color: #f0f2f6 !important;
color: black;
border-radius: 5px;
}
div.stSlider > label {
color: black;
}
div.stSlider > div > div > div[data-baseweb="slider"] {
background-color: #f0f2f6 !important;
border-radius: 5px;
}
div.stCheckbox > label {
color: black;
}
</style>
"""
def main():
st.set_page_config(
page_title="AI Text Generator",
page_icon=":speech_balloon:",
layout="wide",
initial_sidebar_state="expanded",
)
st.markdown(custom_css, unsafe_allow_html=True)
st.title("AI Text Generator :speech_balloon:")
if "chat_history" not in st.session_state:
st.session_state["chat_history"] = []
with st.sidebar:
st.title("Chat History")
clear_button_key = "clear_sidebar"
if st.button("Clear History", key=clear_button_key):
st.session_state["chat_history"] = []
if "chat" in st.session_state:
del st.session_state["chat"]
st.rerun()
st.subheader("Recent:")
for i, message in enumerate(st.session_state["chat_history"]):
if message["role"] == "user":
st.markdown(f"**Input {i//2 + 1}:** {message['content']}")
if "generated" not in st.session_state:
st.session_state["generated"] = False
if not st.session_state["generated"]:
topic = st.text_area("Enter Topic:")
with st.container():
col1, col2, col3 = st.columns(3)
with col1:
output_format = st.selectbox("Output Format:", ["Story", "Poem", "Article", "Code", None])
with col2:
tone = st.selectbox("Tone:", ["Formal", "Informal", "Humorous", "Technical", None])
with col3:
num_responses = st.number_input("Responses:", min_value=1, max_value=5, value=1, step=1)
with st.container():
length = st.slider("Length (words):", 0, 300, 100)
creative_mode = st.checkbox("Creative Mode")
fact_checking = st.checkbox("Fact-Check")
model = initialize_gemini()
if model is None:
st.error("Chatbot initialization failed. Check your API key.")
return
if "chat" not in st.session_state:
try:
st.session_state["chat"] = model.start_chat(history=st.session_state["chat_history"])
except Exception as e:
st.error(f"Error starting chat session: {e}")
return
chat = st.session_state["chat"]
if st.button("Generate Text"):
if not topic:
st.warning("Please enter a topic.")
else:
with st.spinner(f"Generating"):
response = get_gemini_response(model, topic, output_format, tone, length, num_responses, creative_mode, fact_checking, chat)
if response:
st.session_state["generated_text"] = response
st.session_state["topic"] = topic
st.session_state["chat_history"].append({"role": "user", "content": topic})
st.session_state["chat_history"].append({"role": "gemini", "content": response})
st.session_state["generated"] = True
st.rerun()
else:
st.error("Failed to get a response from the chatbot.")
else:
st.subheader("Generated Text:")
st.markdown(f'<div class="gemini-message">{st.session_state["generated_text"]}</div>', unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
like = st.button("Like")
with col2:
dislike = st.button("Dislike")
if like:
st.success("Thanks for your feedback!")
if dislike:
st.error("We appreciate your feedback.")
if st.button("Generate Again"):
st.session_state["generated"] = False
del st.session_state["generated_text"]
st.rerun()
if __name__ == "__main__":
main() |