import streamlit as st import openai import hashlib import random # Set the OpenAI API key from Streamlit secrets openai.api_key = st.secrets["OPENAI_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: """ Creates a custom prompt based on the user's selected template and tone. """ 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: """ Apply additional transformations to simulate human-like writing. """ # List of phrases to introduce conversational tones conversational_inserts = [ "Honestly,", "Frankly speaking,", "In a nutshell,", "To put it simply,", "If I may add," ] # Substitute some formal words with informal counterparts 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) # Add conversational inserts randomly 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: """ Generates humanized text using OpenAI's API based on the prompt. """ try: response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "Write as if you're a real person, natural and relatable."}, {"role": "user", "content": prompt} ], max_tokens=max_tokens, temperature=temperature, top_p=0.9, frequency_penalty=0.4, presence_penalty=0.8, ) # Refine the response to add human-like nuances refined_text = refine_text(response.choices[0].message.content.strip()) return refined_text 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.") # Input fields 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 and display humanized text 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) # Display result if humanized_text: st.subheader("💡 Humanized Text:") st.write(humanized_text) else: st.warning("Please enter text to humanize.") # Feedback section 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!") # Here, you can add code to save the feedback if needed if __name__ == "__main__": main()