File size: 4,981 Bytes
27e1cea
29229fb
27e1cea
 
 
29229fb
 
27e1cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29229fb
27e1cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29229fb
27e1cea
29229fb
27e1cea
 
29229fb
 
 
 
 
 
 
 
 
 
 
 
 
 
27e1cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29229fb
27e1cea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()