File size: 5,779 Bytes
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
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()