Dhruv1102 commited on
Commit
27e1cea
Β·
verified Β·
1 Parent(s): 23085b5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -0
app.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import openai
3
+ import hashlib
4
+ import random
5
+
6
+ # Set the OpenAI API key from Streamlit secrets
7
+ openai.api_key = st.secrets["OPENAI_API_KEY"]
8
+
9
+ # Cache responses to avoid redundant API calls
10
+ @st.cache_data
11
+ def get_cached_response(key, response=None):
12
+ if response:
13
+ st.session_state[key] = response
14
+ return st.session_state.get(key)
15
+
16
+ def create_prompt(prompt: str, template: str, tone: str) -> str:
17
+ """
18
+ Creates a custom prompt based on the user's selected template and tone.
19
+ """
20
+ templates = {
21
+ "Formal": f"Please make this sound professional and polished:\n\n{prompt}",
22
+ "Empathetic": f"Express warmth and empathy:\n\n{prompt}",
23
+ "Friendly": f"Make it casual and friendly:\n\n{prompt}",
24
+ "Concise": f"Summarize this as clearly as possible:\n\n{prompt}",
25
+ "Creative": f"Add a fun, engaging twist:\n\n{prompt}",
26
+ "General": f"Make this sound natural and conversational:\n\n{prompt}",
27
+ }
28
+ custom_prompt = templates.get(template, f"Make this sound natural and conversational:\n\n{prompt}")
29
+
30
+ tones = {
31
+ "Warm": "Use a warm, approachable tone.",
32
+ "Confident": "Sound friendly but confident.",
33
+ "Apologetic": "Make it sound honest and genuine.",
34
+ "Neutral": "Keep it straightforward and clear.",
35
+ "Optimistic": "Add a hopeful, upbeat tone.",
36
+ "Excited": "Make it energetic and enthusiastic."
37
+ }
38
+ tone_instruction = tones.get(tone, "Keep it natural and relatable.")
39
+ return f"{tone_instruction}\n\n{custom_prompt}"
40
+
41
+ def refine_text(text: str) -> str:
42
+ """
43
+ Apply additional transformations to simulate human-like writing.
44
+ """
45
+ # List of phrases to introduce conversational tones
46
+ conversational_inserts = [
47
+ "Honestly,", "Frankly speaking,", "In a nutshell,", "To put it simply,", "If I may add,"
48
+ ]
49
+
50
+ # Substitute some formal words with informal counterparts
51
+ replacements = {
52
+ "do not": "don't", "cannot": "can't", "will not": "won't",
53
+ "it is": "it's", "let us": "let's", "for example": "like,"
54
+ }
55
+ for formal, casual in replacements.items():
56
+ text = text.replace(formal, casual, 1)
57
+
58
+ # Add conversational inserts randomly
59
+ if random.random() > 0.5:
60
+ insert = random.choice(conversational_inserts)
61
+ sentences = text.split(".")
62
+ if len(sentences) > 2:
63
+ index = random.randint(1, len(sentences) - 2)
64
+ sentences.insert(index, insert)
65
+ text = ". ".join(sentences).replace("..", ".")
66
+
67
+ return text.strip()
68
+
69
+ def generate_text(prompt: str, max_tokens: int, temperature: float) -> str:
70
+ """
71
+ Generates humanized text using OpenAI's API based on the prompt.
72
+ """
73
+ try:
74
+ response = openai.ChatCompletion.create(
75
+ model="gpt-3.5-turbo",
76
+ messages=[
77
+ {"role": "system", "content": "Write as if you're a real person, natural and relatable."},
78
+ {"role": "user", "content": prompt}
79
+ ],
80
+ max_tokens=max_tokens,
81
+ temperature=temperature,
82
+ top_p=0.9,
83
+ frequency_penalty=0.4,
84
+ presence_penalty=0.8,
85
+ )
86
+
87
+ # Refine the response to add human-like nuances
88
+ refined_text = refine_text(response.choices[0].message.content.strip())
89
+ return refined_text
90
+ except Exception as e:
91
+ st.error(f"Error generating text: {e}")
92
+ return None
93
+
94
+ def main():
95
+ st.set_page_config(page_title="HumanizeIt", page_icon="πŸ“", layout="wide")
96
+ st.title("πŸ“ HumanizeIt")
97
+ st.write("Transform your text into something more conversational and human-like.")
98
+
99
+ # Input fields
100
+ st.markdown("### Enter text to humanize:")
101
+ prompt = st.text_area("", height=150)
102
+
103
+ with st.expander("Advanced Options"):
104
+ col1, col2 = st.columns(2)
105
+ with col1:
106
+ template = st.selectbox("Choose a Template:", ["General", "Formal", "Friendly", "Empathetic", "Concise", "Creative"])
107
+ max_tokens = st.slider("Max Tokens:", 50, 300, 150)
108
+ with col2:
109
+ tone = st.selectbox("Select a Tone:", ["Neutral", "Optimistic", "Confident", "Apologetic", "Warm", "Excited"])
110
+ temperature = st.slider("Creativity Level:", 0.1, 1.0, 0.7)
111
+
112
+ # Generate and display humanized text
113
+ generate_button = st.button("✨ Generate Humanized Text")
114
+ if generate_button:
115
+ if prompt.strip():
116
+ with st.spinner("Generating..."):
117
+ user_prompt = create_prompt(prompt, template, tone)
118
+ cache_key = hashlib.md5(user_prompt.encode()).hexdigest()
119
+ cached_response = get_cached_response(cache_key)
120
+
121
+ if cached_response:
122
+ st.write("Retrieved from cache.")
123
+ humanized_text = cached_response
124
+ else:
125
+ humanized_text = generate_text(user_prompt, max_tokens, temperature)
126
+ if humanized_text:
127
+ get_cached_response(cache_key, humanized_text)
128
+
129
+ # Display result
130
+ if humanized_text:
131
+ st.subheader("πŸ’‘ Humanized Text:")
132
+ st.write(humanized_text)
133
+ else:
134
+ st.warning("Please enter text to humanize.")
135
+
136
+ # Feedback section
137
+ st.markdown("---")
138
+ st.subheader("Your Feedback Matters!")
139
+ feedback = st.radio("Was this helpful?", ["πŸ‘ Yes", "πŸ‘Ž No", "😐 Neutral"], horizontal=True)
140
+ additional_feedback = st.text_input("Any suggestions or comments?")
141
+
142
+ if st.button("Submit Feedback"):
143
+ st.success("Thank you for your feedback!")
144
+ # Here, you can add code to save the feedback if needed
145
+
146
+ if __name__ == "__main__":
147
+ main()