DrishtiSharma commited on
Commit
ce4e83c
·
verified ·
1 Parent(s): d5d68fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -49
app.py CHANGED
@@ -106,69 +106,65 @@ app = st.session_state["app"]
106
 
107
  # Function to invoke the agent and generate a response
108
  def enforce_word_limit(text, limit):
109
- """Strictly enforce the word limit by truncating extra words."""
110
- words = re.findall(r'\b\w+\b', text)
111
- return ' '.join(words[:limit]) if len(words) > limit else text
112
 
113
  def detect_unexpected_english(text, selected_language):
114
  """Detect unintended English words when another language is selected."""
115
  if selected_language != "English":
116
- english_words = re.findall(r'\b(?:is|the|and|or|in|on|at|to|with|for|of|by|it|that|this|was|he|she|they|we|you|I)\b', text)
117
- return len(english_words) > 5 # Allow minor tolerance
 
 
118
 
119
  def generate_response(topic, length, selected_language):
120
  if not app or not hasattr(app, "graph"):
121
  st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
122
  return {"response": "Error: Agents not initialized."}
123
 
124
- # **Dynamically Allocate Section Limits Based on Length**
125
  intro_limit = max(40, length // 6)
126
  body_limit = max(80, length - intro_limit - (length // 6))
127
  conclusion_limit = length - (intro_limit + body_limit)
128
- num_sections = min(4, max(2, length // 150)) # 2-4 sections based on length
129
 
130
- # **Strict Prompt with Hard Stop**
131
  refined_prompt = f"""
132
- Write a **structured, concise, and well-formed** essay on "{topic}" in {selected_language}.
133
 
134
- **Word Limit:** EXACTLY {length} words. **DO NOT exceed or fall short.**
135
- **Language:** Use only {selected_language}. **No English unless explicitly requested.**
136
 
137
- **Essay Structure (STRICTLY FOLLOWED):**
138
- - **Title:** Maximum 10 words.
139
- - **Introduction ({intro_limit} words max)** Define topic, give thesis, and preview key points.
140
  - **Main Body ({body_limit} words max, {num_sections} sections)**:
141
  - Each section has **one key idea**.
142
- - **DO NOT exceed section limits**.
143
- - Use **simple, precise sentences**.
144
  - **Conclusion ({conclusion_limit} words max)**:
145
- - Summarize key points **without repetition**.
146
- - Reinforce thesis and end with a strong closing line.
147
-
148
- **HARD RULES:**
149
- - **STOP at exactly {length} words**. No extra words.
150
- - **Do not exceed assigned section limits**.
151
- - **Avoid redundancy and repetition**.
152
- - **Keep sentences concise and natural**.
153
-
154
- STOP WRITING IMMEDIATELY after {length} words.
155
  """
156
 
157
- # **Invoke AI with a STRONG Limit on Tokens**
158
  response = app.graph.invoke(input={
159
  "topic": topic,
160
  "length": length,
161
  "prompt": refined_prompt,
162
  "language": selected_language,
163
- "max_tokens": int(length * 0.75) # STRONG cap (75 tokens per 100 words)
164
  })
165
 
166
- # **Final Hard Stop on Word Limit**
167
  essay_text = enforce_word_limit(response.get("essay", ""), length)
168
 
169
- # **Check for Unwanted English Words**
170
  if detect_unexpected_english(essay_text, selected_language):
171
- return {"response": f"⚠️ Warning: Some English words were detected in the {selected_language} essay. Try regenerating."}
172
 
173
  return {"essay": essay_text}
174
 
@@ -202,7 +198,7 @@ with tab1:
202
  with st.spinner("⏳ Generating your essay..."):
203
  response = None
204
  if app:
205
- response = app.write_essay({"topic": topic})
206
  else:
207
  st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
208
 
@@ -220,27 +216,22 @@ with tab1:
220
 
221
  with col1:
222
  st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
223
- st.markdown(f"#### {essay['header']}")
224
- st.markdown(essay["entry"])
225
 
226
- for para in essay["paragraphs"]:
227
- st.markdown(f"**{para['sub_header']}**")
228
- st.markdown(para["paragraph"])
229
-
230
- st.markdown("**🖊️ Conclusion:**")
231
- st.markdown(essay["conclusion"])
 
 
 
232
 
233
  with col2:
234
  st.markdown("### ✍️ Edit Your Essay:")
235
 
236
- # Combine all parts of the essay into one editable text field
237
- full_essay_text = f"## {essay['header']}\n\n{essay['entry']}\n\n"
238
- for para in essay["paragraphs"]:
239
- full_essay_text += f"### {para['sub_header']}\n{para['paragraph']}\n\n"
240
- full_essay_text += f"**Conclusion:**\n{essay['conclusion']}"
241
-
242
- # Editable text area for the user
243
- edited_essay = st.text_area("Edit Here:", value=full_essay_text, height=300)
244
 
245
  # Save and Download buttons
246
  save_col1, save_col2 = st.columns(2)
@@ -288,7 +279,6 @@ with tab1:
288
  st.error("⚠️ No response received. Please try again.")
289
 
290
 
291
-
292
  # 📊 Tab 2: Workflow Visualization
293
  with tab2:
294
  #st.subheader("📊 Multi-Agent Essay Writer Workflow Viz")
 
106
 
107
  # Function to invoke the agent and generate a response
108
  def enforce_word_limit(text, limit):
109
+ """Ensure the essay is exactly within the word limit."""
110
+ words = text.split()
111
+ return " ".join(words[:limit])
112
 
113
  def detect_unexpected_english(text, selected_language):
114
  """Detect unintended English words when another language is selected."""
115
  if selected_language != "English":
116
+ common_english_words = set(["the", "is", "and", "in", "on", "at", "to", "for", "of", "by", "it", "that", "this", "was", "he", "she", "they", "we", "you", "I"])
117
+ words = text.split()
118
+ english_count = sum(1 for word in words if word.lower() in common_english_words)
119
+ return english_count > 5 # Allow minor tolerance
120
 
121
  def generate_response(topic, length, selected_language):
122
  if not app or not hasattr(app, "graph"):
123
  st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
124
  return {"response": "Error: Agents not initialized."}
125
 
126
+ # **Define Section Limits Dynamically**
127
  intro_limit = max(40, length // 6)
128
  body_limit = max(80, length - intro_limit - (length // 6))
129
  conclusion_limit = length - (intro_limit + body_limit)
130
+ num_sections = min(4, max(2, length // 150))
131
 
132
+ # **Refined Prompt with a Strict Stop**
133
  refined_prompt = f"""
134
+ Write a structured and concise essay on "{topic}" in {selected_language}.
135
 
136
+ **Word Limit:** {length} words. **DO NOT exceed or fall short.**
137
+ **Language:** Only {selected_language}. **No English unless explicitly requested.**
138
 
139
+ **Essay Structure:**
140
+ - **Title:** Max 10 words.
141
+ - **Introduction ({intro_limit} words max)**: Introduce topic, thesis, and key points.
142
  - **Main Body ({body_limit} words max, {num_sections} sections)**:
143
  - Each section has **one key idea**.
144
+ - Follow **strict section word limits**.
145
+ - Avoid redundancy.
146
  - **Conclusion ({conclusion_limit} words max)**:
147
+ - Summarize key points **without repeating introduction**.
148
+ - End with a strong closing statement.
149
+
150
+ **Rules:**
151
+ - **STOP at exactly {length} words**.
152
+ - **Do not repeat conclusion**.
 
 
 
 
153
  """
154
 
155
+ # **Invoke AI with a Token Cap**
156
  response = app.graph.invoke(input={
157
  "topic": topic,
158
  "length": length,
159
  "prompt": refined_prompt,
160
  "language": selected_language,
161
+ "max_tokens": int(length * 0.75) # Limit tokens
162
  })
163
 
 
164
  essay_text = enforce_word_limit(response.get("essay", ""), length)
165
 
 
166
  if detect_unexpected_english(essay_text, selected_language):
167
+ return {"response": f"⚠️ Warning: English detected in {selected_language} essay. Try regenerating."}
168
 
169
  return {"essay": essay_text}
170
 
 
198
  with st.spinner("⏳ Generating your essay..."):
199
  response = None
200
  if app:
201
+ response = generate_response(topic, essay_length, selected_language) # Use improved function
202
  else:
203
  st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
204
 
 
216
 
217
  with col1:
218
  st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
 
 
219
 
220
+ # Ensure proper essay structure
221
+ essay_parts = essay.split("\n\n")
222
+ for part in essay_parts:
223
+ if part.startswith("## "): # Title
224
+ st.markdown(f"#### {part[3:]}")
225
+ elif part.startswith("### "): # Subheadings
226
+ st.markdown(f"**{part[4:]}**")
227
+ else:
228
+ st.markdown(part)
229
 
230
  with col2:
231
  st.markdown("### ✍️ Edit Your Essay:")
232
 
233
+ # Editable text area for user
234
+ edited_essay = st.text_area("Edit Here:", value=essay, height=300)
 
 
 
 
 
 
235
 
236
  # Save and Download buttons
237
  save_col1, save_col2 = st.columns(2)
 
279
  st.error("⚠️ No response received. Please try again.")
280
 
281
 
 
282
  # 📊 Tab 2: Workflow Visualization
283
  with tab2:
284
  #st.subheader("📊 Multi-Agent Essay Writer Workflow Viz")