Files changed (1) hide show
  1. app.py +21 -41
app.py CHANGED
@@ -1,10 +1,10 @@
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
@@ -14,9 +14,6 @@ def get_cached_response(key, response=None):
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}",
@@ -26,7 +23,7 @@ def create_prompt(prompt: str, template: str, tone: str) -> str:
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.",
@@ -39,15 +36,9 @@ def create_prompt(prompt: str, template: str, tone: str) -> str:
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,"
@@ -55,7 +46,6 @@ def refine_text(text: str) -> str:
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(".")
@@ -63,30 +53,25 @@ def refine_text(text: str) -> str:
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
@@ -96,7 +81,6 @@ def main():
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
 
@@ -109,7 +93,6 @@ def main():
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():
@@ -117,7 +100,7 @@ def main():
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
@@ -126,14 +109,12 @@ def main():
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)
@@ -141,7 +122,6 @@ def main():
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()
 
1
  import streamlit as st
2
+ import google.generativeai as genai
3
  import hashlib
4
  import random
5
 
6
+ # Set the Gemini API key
7
+ genai.configure(api_key=st.secrets["GEMINI_API_KEY"])
8
 
9
  # Cache responses to avoid redundant API calls
10
  @st.cache_data
 
14
  return st.session_state.get(key)
15
 
16
  def create_prompt(prompt: str, template: str, tone: str) -> str:
 
 
 
17
  templates = {
18
  "Formal": f"Please make this sound professional and polished:\n\n{prompt}",
19
  "Empathetic": f"Express warmth and empathy:\n\n{prompt}",
 
23
  "General": f"Make this sound natural and conversational:\n\n{prompt}",
24
  }
25
  custom_prompt = templates.get(template, f"Make this sound natural and conversational:\n\n{prompt}")
26
+
27
  tones = {
28
  "Warm": "Use a warm, approachable tone.",
29
  "Confident": "Sound friendly but confident.",
 
36
  return f"{tone_instruction}\n\n{custom_prompt}"
37
 
38
  def refine_text(text: str) -> str:
 
 
 
 
39
  conversational_inserts = [
40
  "Honestly,", "Frankly speaking,", "In a nutshell,", "To put it simply,", "If I may add,"
41
  ]
 
 
42
  replacements = {
43
  "do not": "don't", "cannot": "can't", "will not": "won't",
44
  "it is": "it's", "let us": "let's", "for example": "like,"
 
46
  for formal, casual in replacements.items():
47
  text = text.replace(formal, casual, 1)
48
 
 
49
  if random.random() > 0.5:
50
  insert = random.choice(conversational_inserts)
51
  sentences = text.split(".")
 
53
  index = random.randint(1, len(sentences) - 2)
54
  sentences.insert(index, insert)
55
  text = ". ".join(sentences).replace("..", ".")
56
+
57
  return text.strip()
58
+
59
  def generate_text(prompt: str, max_tokens: int, temperature: float) -> str:
 
 
 
60
  try:
61
+ model = genai.GenerativeModel("gemini-pro")
62
+ response = model.generate_content(prompt, generation_config={
63
+ "temperature": temperature,
64
+ "max_output_tokens": max_tokens,
65
+ "top_p": 0.9,
66
+ "top_k": 40
67
+ })
68
+
69
+ if hasattr(response, "text"):
70
+ return refine_text(response.text)
71
+ else:
72
+ st.error("No response text returned from Gemini.")
73
+ return None
74
+
 
 
75
  except Exception as e:
76
  st.error(f"Error generating text: {e}")
77
  return None
 
81
  st.title("πŸ“ HumanizeIt")
82
  st.write("Transform your text into something more conversational and human-like.")
83
 
 
84
  st.markdown("### Enter text to humanize:")
85
  prompt = st.text_area("", height=150)
86
 
 
93
  tone = st.selectbox("Select a Tone:", ["Neutral", "Optimistic", "Confident", "Apologetic", "Warm", "Excited"])
94
  temperature = st.slider("Creativity Level:", 0.1, 1.0, 0.7)
95
 
 
96
  generate_button = st.button("✨ Generate Humanized Text")
97
  if generate_button:
98
  if prompt.strip():
 
100
  user_prompt = create_prompt(prompt, template, tone)
101
  cache_key = hashlib.md5(user_prompt.encode()).hexdigest()
102
  cached_response = get_cached_response(cache_key)
103
+
104
  if cached_response:
105
  st.write("Retrieved from cache.")
106
  humanized_text = cached_response
 
109
  if humanized_text:
110
  get_cached_response(cache_key, humanized_text)
111
 
 
112
  if humanized_text:
113
  st.subheader("πŸ’‘ Humanized Text:")
114
  st.write(humanized_text)
115
  else:
116
  st.warning("Please enter text to humanize.")
117
 
 
118
  st.markdown("---")
119
  st.subheader("Your Feedback Matters!")
120
  feedback = st.radio("Was this helpful?", ["πŸ‘ Yes", "πŸ‘Ž No", "😐 Neutral"], horizontal=True)
 
122
 
123
  if st.button("Submit Feedback"):
124
  st.success("Thank you for your feedback!")
 
125
 
126
  if __name__ == "__main__":
127
  main()