DrishtiSharma commited on
Commit
d1acdde
·
verified ·
1 Parent(s): 9d335e5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -48
app.py CHANGED
@@ -104,60 +104,65 @@ if st.session_state["app"] is None:
104
  app = st.session_state["app"]
105
 
106
  # Function to invoke the agent and generate a response
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  def generate_response(topic, length, selected_language):
108
  if not app or not hasattr(app, "graph"):
109
  st.error("Agents are not initialized. Please check the system or restart the app.")
110
  return {"response": "Error: Agents not initialized."}
111
 
112
- # Define section allocations dynamically based on length
113
- if length <= 300:
114
- intro_limit = length // 5 # Shorter intro (~20% of total)
115
- body_limit = length // 2 # 2-3 key sections only (~50% of total)
116
- conclusion_limit = length // 5 # Brief closing (~20% of total)
117
- num_sections = 2 # Fewer key points
118
- elif length <= 400:
119
- intro_limit = length // 6 # Slightly shorter intro (~17% of total)
120
- body_limit = length // 1.8 # Allows more depth (~55% of total)
121
- conclusion_limit = length // 6 # Balanced closing (~17% of total)
122
- num_sections = 3 # More sections
123
  else:
124
- intro_limit = length // 7 # Even shorter intro (~15% of total)
125
- body_limit = length // 1.7 # More depth in body (~60% of total)
126
- conclusion_limit = length // 7 # Shorter but strong closing (~15% of total)
127
- num_sections = 4 # Maximum sections for deeper discussion
128
 
129
- # Improved Structured Prompt with Language Reinforcement
130
  refined_prompt = f"""
131
- Write a well-structured, informative, and engaging essay on "{topic}" strictly in {selected_language}.
132
-
133
- Word Limit: Exactly {length} words. Do not exceed or fall short of this limit.
134
- Use native linguistic style and expressions from {selected_language}.
135
-
136
- Structure:
137
- - Title: Maximum 10 words
138
- - Introduction ({intro_limit} words max):
139
- - Clearly define the topic and its relevance.
140
- - Provide a strong thesis statement.
141
- - Outline key points covered in the essay.
142
- - Main Body ({body_limit} words max):
143
- - Cover {num_sections} key aspects only.
144
- - Each section must have:
145
- - A clear subheading.
146
- - A concise topic sentence with supporting details.
147
- - Examples, statistics, or historical references (if relevant).
148
- - Do not exceed section limits.
149
- - Conclusion ({conclusion_limit} words max):
150
- - Summarize key insights without repetition.
151
- - Reinforce thesis based on discussion.
152
- - End with a strong closing statement, such as a reflection or call to action.
153
-
154
- Rules:
155
- - Write only in {selected_language}. Do not use English unless explicitly requested.
156
- - Do not exceed {length} words. Hard limit.
157
- - Use concise, direct, and impactful language.
158
- - Avoid redundancy and unnecessary filler.
159
- - Merge similar ideas for natural flow.
160
- - Stop exactly at {length} words. Do not go over.
161
  """
162
 
163
  # Invoke AI model with enforced word limit
@@ -166,10 +171,17 @@ def generate_response(topic, length, selected_language):
166
  "length": length,
167
  "prompt": refined_prompt,
168
  "language": selected_language,
169
- "max_tokens": int(length * 1.05) # Ensures strict word cap
170
  })
171
 
172
- return response
 
 
 
 
 
 
 
173
 
174
 
175
 
 
104
  app = st.session_state["app"]
105
 
106
  # Function to invoke the agent and generate a response
107
+ import re
108
+
109
+ def enforce_word_limit(text, limit):
110
+ """Enforces strict word limit by truncating extra words."""
111
+ words = re.findall(r'\b\w+\b', text)
112
+ return ' '.join(words[:limit]) if len(words) > limit else text
113
+
114
+ def detect_unexpected_english(text, selected_language):
115
+ """Detects unintended English words when another language is selected."""
116
+ if selected_language != "English":
117
+ 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)
118
+ return len(english_words) > 5 # Allow a small tolerance
119
+
120
  def generate_response(topic, length, selected_language):
121
  if not app or not hasattr(app, "graph"):
122
  st.error("Agents are not initialized. Please check the system or restart the app.")
123
  return {"response": "Error: Agents not initialized."}
124
 
125
+ # Dynamically adjust structure based on length
126
+ if length <= 250:
127
+ intro_limit, body_limit, conclusion_limit = length // 5, length // 2, length // 5
128
+ num_sections = 2 # Shorter essays should have fewer sections
129
+ elif length <= 350:
130
+ intro_limit, body_limit, conclusion_limit = length // 6, length // 1.8, length // 6
131
+ num_sections = 3
 
 
 
 
132
  else:
133
+ intro_limit, body_limit, conclusion_limit = length // 7, length // 1.7, length // 7
134
+ num_sections = 4
 
 
135
 
136
+ # Optimized Structured Prompt
137
  refined_prompt = f"""
138
+ Write a **well-structured, informative, and engaging** essay on "{topic}" **strictly in {selected_language}.**
139
+
140
+ **Word Limit:** Exactly {length} words. **Do not exceed or fall short of this limit.**
141
+ **Language Rules:** Use natural linguistic style from {selected_language}. **Do not use English** unless explicitly requested.
142
+
143
+ **Essay Structure:**
144
+ - **Title**: Max 10 words.
145
+ - **Introduction ({intro_limit} words max)**:
146
+ - Clearly define the topic and its significance.
147
+ - Provide a strong thesis statement.
148
+ - Preview the key points covered in the essay.
149
+ - **Main Body ({body_limit} words max, {num_sections} sections)**:
150
+ - Each section must have:
151
+ - A **clear subheading**.
152
+ - A concise topic sentence with supporting details.
153
+ - Relevant **examples, statistics, or historical references**.
154
+ - Maintain natural **flow** between sections.
155
+ - **Conclusion ({conclusion_limit} words max)**:
156
+ - Summarize key insights **without repetition**.
157
+ - Reinforce the thesis **based on discussion**.
158
+ - End with a strong **closing statement** (reflection or call to action).
159
+
160
+ **Hard Rules:**
161
+ - **Use only {selected_language}**. No English unless explicitly requested.
162
+ - **Do not exceed {length} words.** Absolute limit.
163
+ - **Write concisely and avoid fluff**. No redundancy.
164
+ - **Merge similar ideas** to maintain smooth readability.
165
+ - **Ensure strict adherence to section word limits**.
 
 
166
  """
167
 
168
  # Invoke AI model with enforced word limit
 
171
  "length": length,
172
  "prompt": refined_prompt,
173
  "language": selected_language,
174
+ "max_tokens": length + 10 # Small buffer for better trimming
175
  })
176
 
177
+ # Strict word limit enforcement
178
+ essay_text = enforce_word_limit(response.get("essay", ""), length)
179
+
180
+ # Detect unintended English words in non-English essays
181
+ if detect_unexpected_english(essay_text, selected_language):
182
+ return {"response": f"⚠️ Warning: Some English words were detected in the {selected_language} essay. Try regenerating."}
183
+
184
+ return {"essay": essay_text}
185
 
186
 
187