Rathapoom commited on
Commit
35c5870
·
verified ·
1 Parent(s): dbcd17e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -59
app.py CHANGED
@@ -549,6 +549,14 @@ def init_session_state():
549
  st.session_state.clear_input = False
550
  if 'text_input' not in st.session_state:
551
  st.session_state.text_input = ""
 
 
 
 
 
 
 
 
552
 
553
  def init_theme_state():
554
  """Initialize theme-specific state variables"""
@@ -1626,11 +1634,12 @@ def handle_ending_mode(text: str):
1626
  "is_corrected": False,
1627
  "is_correct": True,
1628
  "timestamp": datetime.now().isoformat(),
1629
- "remaining_sentences": remaining # เพิ่มจำนวนประโยคที่เหลือ
1630
  })
1631
 
1632
  # Decrease remaining count for user's sentence
1633
- remaining -= 1
 
1634
 
1635
  if remaining > 0:
1636
  # Generate AI's ending continuation
@@ -1645,15 +1654,12 @@ def handle_ending_mode(text: str):
1645
  "role": "AI",
1646
  "content": ai_response,
1647
  "timestamp": datetime.now().isoformat(),
1648
- "remaining_sentences": remaining # เพิ่มจำนวนประโยคที่เหลือ
1649
  })
1650
 
1651
- # Decrease for AI's sentence
1652
- remaining -= 1
1653
-
1654
- # Update remaining sentences in session state
1655
- st.session_state.sentences_to_end = remaining
1656
-
1657
  else:
1658
  # Generate final ending
1659
  final_response = generate_final_ending(
@@ -1674,13 +1680,15 @@ def handle_ending_mode(text: str):
1674
  complete_story()
1675
 
1676
  # Clear input and rerun
1677
- st.session_state.story_input_area = ""
 
1678
  st.rerun()
1679
 
1680
  except Exception as e:
1681
  logging.error(f"Error in ending mode: {str(e)}")
1682
  st.error("เกิดข้อผิดพลาดในโหมดจบเรื่อง กรุณาลองใหม่อีกครั้ง")
1683
 
 
1684
  def generate_final_ending(story: List[dict], ending_type: str) -> str:
1685
  """Generate the final ending sentence based on the story and chosen ending type"""
1686
  try:
@@ -1756,7 +1764,7 @@ def generate_ending_continuation(text: str, ending_type: str, remaining_sentence
1756
  - Build towards joy, success, or resolution
1757
  - Use uplifting and positive language
1758
  - Connect to previous story elements
1759
- """,
1760
  "Mysterious Ending": """
1761
  Role: Mystery writer creating intrigue
1762
  Goal: Leave readers thinking and wondering
@@ -1764,7 +1772,7 @@ def generate_ending_continuation(text: str, ending_type: str, remaining_sentence
1764
  - Add subtle hints and clues
1765
  - Create atmospheric descriptions
1766
  - Leave some questions unanswered
1767
- """,
1768
  "Lesson Learned": """
1769
  Role: Moral story concluder
1770
  Goal: Incorporate meaningful life lessons
@@ -1772,7 +1780,7 @@ def generate_ending_continuation(text: str, ending_type: str, remaining_sentence
1772
  - Connect actions to consequences
1773
  - Show character growth
1774
  - Express the moral naturally
1775
- """,
1776
  "Surprise Ending": """
1777
  Role: Plot twist creator
1778
  Goal: Deliver unexpected but satisfying conclusion
@@ -1780,11 +1788,11 @@ def generate_ending_continuation(text: str, ending_type: str, remaining_sentence
1780
  - Plant subtle hints earlier
1781
  - Subvert expectations logically
1782
  - Maintain story coherence
1783
- """
1784
  }
1785
 
1786
  response = client.chat.completions.create(
1787
- model="gpt-4",
1788
  messages=[
1789
  {
1790
  "role": "system",
@@ -1792,10 +1800,11 @@ def generate_ending_continuation(text: str, ending_type: str, remaining_sentence
1792
  {ending_prompts[ending_type]}
1793
 
1794
  Additional Rules:
1795
- - You have {remaining_sentences} sentences to conclude
1796
- - Each response should be max 2 sentences
1797
- - Build towards the finale naturally
1798
- - Connect to previous story elements
 
1799
  """
1800
  },
1801
  {
@@ -1806,13 +1815,14 @@ def generate_ending_continuation(text: str, ending_type: str, remaining_sentence
1806
  max_tokens=100,
1807
  temperature=0.7
1808
  )
1809
-
1810
  return response.choices[0].message.content.strip()
1811
 
1812
  except Exception as e:
1813
- logging.error(f"Error generating ending: {str(e)}")
1814
  return "The story moved towards its conclusion..."
1815
 
 
1816
  def complete_story():
1817
  """Handle story completion and celebration"""
1818
  st.balloons() # แสดงเอฟเฟคฉลอง
@@ -2173,11 +2183,16 @@ def show_story_input():
2173
  # If clear_input flag is True, reset it
2174
  if st.session_state.clear_input:
2175
  st.session_state.clear_input = False
 
 
 
 
 
2176
 
2177
  # Input area
2178
  text_input = st.text_area(
2179
  "เขียนต่อจากเรื่องราว | Continue the story:",
2180
- value=default_value,
2181
  height=100,
2182
  key="story_input_area",
2183
  help="พิมพ์ประโยคภาษาอังกฤษเพื่อต่อเรื่อง",
@@ -2194,7 +2209,6 @@ def show_story_input():
2194
  if not text_input.strip():
2195
  st.warning("กรุณาเขียนข้อความก่อนส่ง")
2196
  return
2197
-
2198
  try:
2199
  with st.spinner("กำลังวิเคราะห์ประโยค..."):
2200
  handle_story_submission(text_input.strip())
@@ -2216,6 +2230,12 @@ def handle_story_submission(text: str):
2216
  st.error("กรุณาเลือกธีมเรื่องราวก่อนเริ่มเขียน")
2217
  return
2218
 
 
 
 
 
 
 
2219
  try:
2220
  # Get feedback
2221
  feedback_data = provide_feedback(text, st.session_state.level)
@@ -2242,7 +2262,7 @@ def handle_story_submission(text: str):
2242
  # Generate AI continuation
2243
  try:
2244
  logging.info("Attempting to generate AI continuation...")
2245
- # ใช้ข้อความที่ถูกต้องสำหรับการต่อเรื่อง
2246
  text_for_continuation = feedback_data['corrected'] if feedback_data.get('has_errors') else text
2247
 
2248
  ai_response = generate_story_continuation(text_for_continuation, st.session_state.level)
@@ -2259,7 +2279,7 @@ def handle_story_submission(text: str):
2259
  logging.info("AI response added to story successfully")
2260
  else:
2261
  logging.error("AI generated empty response")
2262
- # กรณีที่ AI ไม่สร้างประโยค ให้สร้างประโยคง่ายๆ ตาม theme
2263
  fallback_response = generate_fallback_response(st.session_state.current_theme, st.session_state.level)
2264
  st.session_state.story.append({
2265
  "role": "AI",
@@ -2268,7 +2288,7 @@ def handle_story_submission(text: str):
2268
  })
2269
  except Exception as e:
2270
  logging.error(f"Error generating AI continuation: {str(e)}")
2271
- # สร้าง fallback response เมื่อเกิดข้อผิดพลาด
2272
  fallback_response = generate_fallback_response(st.session_state.current_theme, st.session_state.level)
2273
  st.session_state.story.append({
2274
  "role": "AI",
@@ -2289,6 +2309,7 @@ def handle_story_submission(text: str):
2289
  logging.error(f"Error in story submission: {str(e)}")
2290
  raise
2291
 
 
2292
  def generate_fallback_response(theme_id: str, level: str) -> str:
2293
  """Generate a simple fallback response when AI continuation fails"""
2294
  try:
@@ -2362,9 +2383,11 @@ def main():
2362
  if 'ending_mode' not in st.session_state:
2363
  st.session_state.ending_mode = False
2364
  if 'sentences_to_end' not in st.session_state:
2365
- st.session_state.sentences_to_end = 5
2366
  if 'ending_type' not in st.session_state:
2367
  st.session_state.ending_type = None
 
 
2368
 
2369
  # Add watermark
2370
  st.markdown("""
@@ -2394,7 +2417,7 @@ def main():
2394
  else:
2395
  # Show story progress if story exists
2396
  if st.session_state.story:
2397
- # แสดงความคืบหน้าของเรื่อง
2398
  total_sentences = len(st.session_state.story)
2399
  st.markdown(f"""
2400
  <div style="
@@ -2407,7 +2430,7 @@ def main():
2407
  📊 ความยาวเรื่อง: {total_sentences} ประโยค
2408
  </div>
2409
  <div class="progress-bar">
2410
- <div class="progress-bar-fill" style="width: {min(total_sentences * 10, 100)}%;"></div>
2411
  </div>
2412
  <div style="font-size: 0.9em; color: #666; margin-top: 5px;">
2413
  เรื่องควรยาว 10-20 ประโยค เพื่อความสมบูรณ์
@@ -2415,16 +2438,16 @@ def main():
2415
  </div>
2416
  """, unsafe_allow_html=True)
2417
 
2418
- # แสดงตัวเลือกจบเรื่องเมื่อเรื่องยาวพอ
2419
- if (total_sentences >= 10 and not st.session_state.get('ending_mode')):
2420
  st.markdown("### 🎭 ต้องการจบเรื่องหรือไม่?")
2421
  ending_type = st.radio(
2422
  "เลือกวิธีจบเรื่อง:",
2423
  options=[
2424
- "Happy Ending - จบแบบมีความสุข",
2425
- "Mysterious Ending - จบแบบทิ้งท้ายให้คิดต่อ",
2426
- "Lesson Learned - จบแบบได้ข้อคิด",
2427
- "Surprise Ending - จบแบบพลิกความคาดหมาย"
2428
  ],
2429
  index=0,
2430
  key="ending_type_selector"
@@ -2433,10 +2456,11 @@ def main():
2433
  if st.button("🎬 เริ่มจบเรื่อง", use_container_width=True):
2434
  st.session_state.ending_mode = True
2435
  st.session_state.ending_type = ending_type
2436
- st.session_state.sentences_to_end = 5
2437
- st.rerun()
 
2438
 
2439
- # แสดงแจ้งเตือนโหมดจบเรื่อง
2440
  if st.session_state.get('ending_mode'):
2441
  remaining = st.session_state.sentences_to_end
2442
  if remaining > 0:
@@ -2447,36 +2471,50 @@ def main():
2447
 
2448
  พยายามเขียนให้เรื่องจบอย่างสมบูรณ์!
2449
  """)
2450
-
2451
- # แสดงส่วนหลัก
2452
- show_main_interface()
2453
-
2454
- # ตรวจสอบการจบเรื่อง
2455
- if st.session_state.get('ending_mode'):
2456
- if st.session_state.sentences_to_end <= 0:
2457
- if not st.session_state.get('story_completed'):
2458
- complete_story()
2459
  st.balloons()
2460
- elif st.session_state.sentences_to_end == 1:
2461
- st.info("⚡ เหลือประโยคสุดท้ายแล้ว! เขียนให้จบอย่างสวยงาม")
2462
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2463
  # Handle reset if needed
2464
  if st.session_state.get('should_reset'):
2465
  reset_story()
2466
  # Reset ending states
2467
  st.session_state.ending_mode = False
2468
- st.session_state.sentences_to_end = 5
2469
  st.session_state.ending_type = None
2470
  st.session_state.story_completed = False
2471
-
2472
- # Handle reset if needed
2473
- if st.session_state.should_reset:
2474
- reset_story()
2475
- # Reset ending mode states
2476
- st.session_state.ending_mode = False
2477
- st.session_state.sentences_to_end = 5
2478
- st.session_state.ending_type = None
2479
-
2480
  # Auto-save progress periodically
2481
  if st.session_state.story:
2482
  auto_save_progress()
@@ -2484,6 +2522,7 @@ def main():
2484
  except Exception as e:
2485
  handle_application_error(e)
2486
 
 
2487
  def check_session_status():
2488
  """Check and maintain session status"""
2489
  try:
 
549
  st.session_state.clear_input = False
550
  if 'text_input' not in st.session_state:
551
  st.session_state.text_input = ""
552
+ if 'ending_mode' not in st.session_state:
553
+ st.session_state.ending_mode = False
554
+ if 'sentences_to_end' not in st.session_state:
555
+ st.session_state.sentences_to_end = 0
556
+ if 'ending_type' not in st.session_state:
557
+ st.session_state.ending_type = None
558
+ if 'story_completed' not in st.session_state:
559
+ st.session_state.story_completed = False
560
 
561
  def init_theme_state():
562
  """Initialize theme-specific state variables"""
 
1634
  "is_corrected": False,
1635
  "is_correct": True,
1636
  "timestamp": datetime.now().isoformat(),
1637
+ "remaining_sentences": remaining # Include remaining sentences
1638
  })
1639
 
1640
  # Decrease remaining count for user's sentence
1641
+ st.session_state.sentences_to_end -= 1
1642
+ remaining = st.session_state.sentences_to_end # Update local variable
1643
 
1644
  if remaining > 0:
1645
  # Generate AI's ending continuation
 
1654
  "role": "AI",
1655
  "content": ai_response,
1656
  "timestamp": datetime.now().isoformat(),
1657
+ "remaining_sentences": remaining
1658
  })
1659
 
1660
+ # Decrease remaining sentences
1661
+ st.session_state.sentences_to_end -= 1
1662
+ remaining = st.session_state.sentences_to_end
 
 
 
1663
  else:
1664
  # Generate final ending
1665
  final_response = generate_final_ending(
 
1680
  complete_story()
1681
 
1682
  # Clear input and rerun
1683
+ st.session_state.text_input = ""
1684
+ st.session_state.clear_input = True
1685
  st.rerun()
1686
 
1687
  except Exception as e:
1688
  logging.error(f"Error in ending mode: {str(e)}")
1689
  st.error("เกิดข้อผิดพลาดในโหมดจบเรื่อง กรุณาลองใหม่อีกครั้ง")
1690
 
1691
+
1692
  def generate_final_ending(story: List[dict], ending_type: str) -> str:
1693
  """Generate the final ending sentence based on the story and chosen ending type"""
1694
  try:
 
1764
  - Build towards joy, success, or resolution
1765
  - Use uplifting and positive language
1766
  - Connect to previous story elements
1767
+ """,
1768
  "Mysterious Ending": """
1769
  Role: Mystery writer creating intrigue
1770
  Goal: Leave readers thinking and wondering
 
1772
  - Add subtle hints and clues
1773
  - Create atmospheric descriptions
1774
  - Leave some questions unanswered
1775
+ """,
1776
  "Lesson Learned": """
1777
  Role: Moral story concluder
1778
  Goal: Incorporate meaningful life lessons
 
1780
  - Connect actions to consequences
1781
  - Show character growth
1782
  - Express the moral naturally
1783
+ """,
1784
  "Surprise Ending": """
1785
  Role: Plot twist creator
1786
  Goal: Deliver unexpected but satisfying conclusion
 
1788
  - Plant subtle hints earlier
1789
  - Subvert expectations logically
1790
  - Maintain story coherence
1791
+ """
1792
  }
1793
 
1794
  response = client.chat.completions.create(
1795
+ model="gpt-4o-mini",
1796
  messages=[
1797
  {
1798
  "role": "system",
 
1800
  {ending_prompts[ending_type]}
1801
 
1802
  Additional Rules:
1803
+ - You have {remaining_sentences} sentences left to conclude the story.
1804
+ - Each response should be maximum 2 sentences.
1805
+ - Build towards the finale naturally.
1806
+ - Ensure coherence with previous story events.
1807
+ - Indicate awareness of the remaining sentences.
1808
  """
1809
  },
1810
  {
 
1815
  max_tokens=100,
1816
  temperature=0.7
1817
  )
1818
+
1819
  return response.choices[0].message.content.strip()
1820
 
1821
  except Exception as e:
1822
+ logging.error(f"Error generating ending continuation: {str(e)}")
1823
  return "The story moved towards its conclusion..."
1824
 
1825
+
1826
  def complete_story():
1827
  """Handle story completion and celebration"""
1828
  st.balloons() # แสดงเอฟเฟคฉลอง
 
2183
  # If clear_input flag is True, reset it
2184
  if st.session_state.clear_input:
2185
  st.session_state.clear_input = False
2186
+
2187
+ # Show remaining sentences if in ending mode
2188
+ if st.session_state.get('ending_mode'):
2189
+ remaining = st.session_state.sentences_to_end
2190
+ st.info(f"🎭 โหมดจบเรื่อง - เหลืออีก {remaining} ประโยค")
2191
 
2192
  # Input area
2193
  text_input = st.text_area(
2194
  "เขียนต่อจากเรื่องราว | Continue the story:",
2195
+ value=st.session_state.get('text_input', ""),
2196
  height=100,
2197
  key="story_input_area",
2198
  help="พิมพ์ประโยคภาษาอังกฤษเพื่อต่อเรื่อง",
 
2209
  if not text_input.strip():
2210
  st.warning("กรุณาเขียนข้อความก่อนส่ง")
2211
  return
 
2212
  try:
2213
  with st.spinner("กำลังวิเคราะห์ประโยค..."):
2214
  handle_story_submission(text_input.strip())
 
2230
  st.error("กรุณาเลือกธีมเรื่องราวก่อนเริ่มเขียน")
2231
  return
2232
 
2233
+ # Check if in ending mode
2234
+ if st.session_state.get('ending_mode'):
2235
+ handle_ending_mode(text)
2236
+ return
2237
+
2238
+ # Regular processing
2239
  try:
2240
  # Get feedback
2241
  feedback_data = provide_feedback(text, st.session_state.level)
 
2262
  # Generate AI continuation
2263
  try:
2264
  logging.info("Attempting to generate AI continuation...")
2265
+ # Use the corrected text if there are errors
2266
  text_for_continuation = feedback_data['corrected'] if feedback_data.get('has_errors') else text
2267
 
2268
  ai_response = generate_story_continuation(text_for_continuation, st.session_state.level)
 
2279
  logging.info("AI response added to story successfully")
2280
  else:
2281
  logging.error("AI generated empty response")
2282
+ # Create a fallback response
2283
  fallback_response = generate_fallback_response(st.session_state.current_theme, st.session_state.level)
2284
  st.session_state.story.append({
2285
  "role": "AI",
 
2288
  })
2289
  except Exception as e:
2290
  logging.error(f"Error generating AI continuation: {str(e)}")
2291
+ # Create a fallback response
2292
  fallback_response = generate_fallback_response(st.session_state.current_theme, st.session_state.level)
2293
  st.session_state.story.append({
2294
  "role": "AI",
 
2309
  logging.error(f"Error in story submission: {str(e)}")
2310
  raise
2311
 
2312
+
2313
  def generate_fallback_response(theme_id: str, level: str) -> str:
2314
  """Generate a simple fallback response when AI continuation fails"""
2315
  try:
 
2383
  if 'ending_mode' not in st.session_state:
2384
  st.session_state.ending_mode = False
2385
  if 'sentences_to_end' not in st.session_state:
2386
+ st.session_state.sentences_to_end = 0 # Set to 0 by default
2387
  if 'ending_type' not in st.session_state:
2388
  st.session_state.ending_type = None
2389
+ if 'story_completed' not in st.session_state:
2390
+ st.session_state.story_completed = False
2391
 
2392
  # Add watermark
2393
  st.markdown("""
 
2417
  else:
2418
  # Show story progress if story exists
2419
  if st.session_state.story:
2420
+ # Display story progress
2421
  total_sentences = len(st.session_state.story)
2422
  st.markdown(f"""
2423
  <div style="
 
2430
  📊 ความยาวเรื่อง: {total_sentences} ประโยค
2431
  </div>
2432
  <div class="progress-bar">
2433
+ <div class="progress-bar-fill" style="width: {min(total_sentences * 5, 100)}%;"></div>
2434
  </div>
2435
  <div style="font-size: 0.9em; color: #666; margin-top: 5px;">
2436
  เรื่องควรยาว 10-20 ประโยค เพื่อความสมบูรณ์
 
2438
  </div>
2439
  """, unsafe_allow_html=True)
2440
 
2441
+ # Show ending options if story is long enough and ending mode is not active
2442
+ if (total_sentences >= 10 and not st.session_state.get('ending_mode') and not st.session_state.get('story_completed')):
2443
  st.markdown("### 🎭 ต้องการจบเรื่องหรือไม่?")
2444
  ending_type = st.radio(
2445
  "เลือกวิธีจบเรื่อง:",
2446
  options=[
2447
+ "Happy Ending",
2448
+ "Mysterious Ending",
2449
+ "Lesson Learned",
2450
+ "Surprise Ending"
2451
  ],
2452
  index=0,
2453
  key="ending_type_selector"
 
2456
  if st.button("🎬 เริ่มจบเรื่อง", use_container_width=True):
2457
  st.session_state.ending_mode = True
2458
  st.session_state.ending_type = ending_type
2459
+ st.session_state.sentences_to_end = 5 # Set the countdown
2460
+ st.success(f"โหมดจบเรื่องเริ่มต้นแล้ว! รูปแบบการจบ: {ending_type}")
2461
+ st.experimental_rerun()
2462
 
2463
+ # Show ending mode notification
2464
  if st.session_state.get('ending_mode'):
2465
  remaining = st.session_state.sentences_to_end
2466
  if remaining > 0:
 
2471
 
2472
  พยายามเขียนให้เรื่องจบอย่างสมบูรณ์!
2473
  """)
2474
+ elif remaining <= 0 and not st.session_state.get('story_completed'):
2475
+ # Story should be marked as completed
2476
+ st.success("🎉 เรื่องราวของคุณจบลงแล้ว!")
 
 
 
 
 
 
2477
  st.balloons()
2478
+ st.session_state.ending_mode = False
2479
+ st.session_state.story_completed = True
2480
 
2481
+ # Display main interface
2482
+ show_main_interface()
2483
+
2484
+ # Handle story completion
2485
+ if st.session_state.get('story_completed'):
2486
+ st.markdown("""
2487
+ <div style="
2488
+ background-color: #e8f5e9;
2489
+ padding: 20px;
2490
+ border-radius: 10px;
2491
+ text-align: center;
2492
+ margin: 20px 0;
2493
+ ">
2494
+ <h2>🎉 ยินดีด้วย! คุณเขียนเรื่องราวจบสมบูรณ์แล้ว</h2>
2495
+ <p>คุณสามารถบันทึกเรื่องราวหรือเริ่มเรื่องใหม่ได้</p>
2496
+ </div>
2497
+ """, unsafe_allow_html=True)
2498
+ # Show save and reset options
2499
+ col1, col2 = st.columns(2)
2500
+ with col1:
2501
+ if st.button("💾 บันทึกเรื่องราว", use_container_width=True):
2502
+ save_completed_story()
2503
+ with col2:
2504
+ if st.button("🔄 เริ่มเรื่องใหม่", use_container_width=True):
2505
+ reset_story()
2506
+ st.experimental_rerun()
2507
+
2508
  # Handle reset if needed
2509
  if st.session_state.get('should_reset'):
2510
  reset_story()
2511
  # Reset ending states
2512
  st.session_state.ending_mode = False
2513
+ st.session_state.sentences_to_end = 0
2514
  st.session_state.ending_type = None
2515
  st.session_state.story_completed = False
2516
+ st.experimental_rerun()
2517
+
 
 
 
 
 
 
 
2518
  # Auto-save progress periodically
2519
  if st.session_state.story:
2520
  auto_save_progress()
 
2522
  except Exception as e:
2523
  handle_application_error(e)
2524
 
2525
+
2526
  def check_session_status():
2527
  """Check and maintain session status"""
2528
  try: