HumanizeIt / app.py
nithadya's picture
update app.py
29229fb verified
raw
history blame
4.98 kB
import streamlit as st
import google.generativeai as genai
import hashlib
import random
# Set the Gemini API key
genai.configure(api_key=st.secrets["GEMINI_API_KEY"])
# Cache responses to avoid redundant API calls
@st.cache_data
def get_cached_response(key, response=None):
if response:
st.session_state[key] = response
return st.session_state.get(key)
def create_prompt(prompt: str, template: str, tone: str) -> str:
templates = {
"Formal": f"Please make this sound professional and polished:\n\n{prompt}",
"Empathetic": f"Express warmth and empathy:\n\n{prompt}",
"Friendly": f"Make it casual and friendly:\n\n{prompt}",
"Concise": f"Summarize this as clearly as possible:\n\n{prompt}",
"Creative": f"Add a fun, engaging twist:\n\n{prompt}",
"General": f"Make this sound natural and conversational:\n\n{prompt}",
}
custom_prompt = templates.get(template, f"Make this sound natural and conversational:\n\n{prompt}")
tones = {
"Warm": "Use a warm, approachable tone.",
"Confident": "Sound friendly but confident.",
"Apologetic": "Make it sound honest and genuine.",
"Neutral": "Keep it straightforward and clear.",
"Optimistic": "Add a hopeful, upbeat tone.",
"Excited": "Make it energetic and enthusiastic."
}
tone_instruction = tones.get(tone, "Keep it natural and relatable.")
return f"{tone_instruction}\n\n{custom_prompt}"
def refine_text(text: str) -> str:
conversational_inserts = [
"Honestly,", "Frankly speaking,", "In a nutshell,", "To put it simply,", "If I may add,"
]
replacements = {
"do not": "don't", "cannot": "can't", "will not": "won't",
"it is": "it's", "let us": "let's", "for example": "like,"
}
for formal, casual in replacements.items():
text = text.replace(formal, casual, 1)
if random.random() > 0.5:
insert = random.choice(conversational_inserts)
sentences = text.split(".")
if len(sentences) > 2:
index = random.randint(1, len(sentences) - 2)
sentences.insert(index, insert)
text = ". ".join(sentences).replace("..", ".")
return text.strip()
def generate_text(prompt: str, max_tokens: int, temperature: float) -> str:
try:
model = genai.GenerativeModel("gemini-pro")
response = model.generate_content(prompt, generation_config={
"temperature": temperature,
"max_output_tokens": max_tokens,
"top_p": 0.9,
"top_k": 40
})
if hasattr(response, "text"):
return refine_text(response.text)
else:
st.error("No response text returned from Gemini.")
return None
except Exception as e:
st.error(f"Error generating text: {e}")
return None
def main():
st.set_page_config(page_title="HumanizeIt", page_icon="πŸ“", layout="wide")
st.title("πŸ“ HumanizeIt")
st.write("Transform your text into something more conversational and human-like.")
st.markdown("### Enter text to humanize:")
prompt = st.text_area("", height=150)
with st.expander("Advanced Options"):
col1, col2 = st.columns(2)
with col1:
template = st.selectbox("Choose a Template:", ["General", "Formal", "Friendly", "Empathetic", "Concise", "Creative"])
max_tokens = st.slider("Max Tokens:", 50, 300, 150)
with col2:
tone = st.selectbox("Select a Tone:", ["Neutral", "Optimistic", "Confident", "Apologetic", "Warm", "Excited"])
temperature = st.slider("Creativity Level:", 0.1, 1.0, 0.7)
generate_button = st.button("✨ Generate Humanized Text")
if generate_button:
if prompt.strip():
with st.spinner("Generating..."):
user_prompt = create_prompt(prompt, template, tone)
cache_key = hashlib.md5(user_prompt.encode()).hexdigest()
cached_response = get_cached_response(cache_key)
if cached_response:
st.write("Retrieved from cache.")
humanized_text = cached_response
else:
humanized_text = generate_text(user_prompt, max_tokens, temperature)
if humanized_text:
get_cached_response(cache_key, humanized_text)
if humanized_text:
st.subheader("πŸ’‘ Humanized Text:")
st.write(humanized_text)
else:
st.warning("Please enter text to humanize.")
st.markdown("---")
st.subheader("Your Feedback Matters!")
feedback = st.radio("Was this helpful?", ["πŸ‘ Yes", "πŸ‘Ž No", "😐 Neutral"], horizontal=True)
additional_feedback = st.text_input("Any suggestions or comments?")
if st.button("Submit Feedback"):
st.success("Thank you for your feedback!")
if __name__ == "__main__":
main()