Rathapoom commited on
Commit
c2f8555
·
verified ·
1 Parent(s): 1fcdf1a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -24
app.py CHANGED
@@ -752,9 +752,9 @@ def generate_story_continuation(user_input: str, level: str) -> str:
752
  }
753
 
754
  try:
755
- # Get recent story context
756
  story_context = '\n'.join([
757
- entry['content'] for entry in st.session_state.story[-3:]
758
  ]) if st.session_state.story else "Story just started"
759
 
760
  # Create prompt
@@ -817,6 +817,7 @@ def generate_story_continuation(user_input: str, level: str) -> str:
817
  logging.error(f"Error generating story continuation: {str(e)}")
818
  return "I'm having trouble continuing the story. Please try again."
819
 
 
820
  def generate_dynamic_story_starter(theme_id: str, level: str) -> Dict[str, str]:
821
  """
822
  Dynamically generate a story starter based on theme and level.
@@ -1646,7 +1647,8 @@ def handle_ending_mode(text: str):
1646
  ai_response = generate_ending_continuation(
1647
  text,
1648
  ending_type=st.session_state.ending_type,
1649
- remaining_sentences=remaining
 
1650
  )
1651
 
1652
  # Add AI response
@@ -1664,7 +1666,8 @@ def handle_ending_mode(text: str):
1664
  # Generate final ending
1665
  final_response = generate_final_ending(
1666
  st.session_state.story,
1667
- st.session_state.ending_type
 
1668
  )
1669
 
1670
  # Add final AI response
@@ -1681,13 +1684,14 @@ def handle_ending_mode(text: str):
1681
  # Clear input and rerun
1682
  st.session_state.text_input = ""
1683
  st.session_state.clear_input = True
1684
- st.rerun() # Using st.rerun() instead of st.experimental_rerun()
1685
 
1686
  except Exception as e:
1687
  logging.error(f"Error in ending mode: {str(e)}")
1688
  st.error("เกิดข้อผิดพลาดในโหมดจบเรื่อง กรุณาลองใหม่อีกครั้ง")
1689
 
1690
- def generate_final_ending(story: List[dict], ending_type: str) -> str:
 
1691
  """Generate the final ending sentence based on the story and chosen ending type"""
1692
  try:
1693
  # Create a comprehensive prompt for the final ending
@@ -1699,39 +1703,78 @@ def generate_final_ending(story: List[dict], ending_type: str) -> str:
1699
  - Brings joy and satisfaction
1700
  - Resolves the main story elements
1701
  - Ends on a positive note
1702
- Maximum 2 sentences.
1703
- """,
1704
  "Mysterious Ending": """
1705
  Create a final mysterious ending sentence that:
1706
  - Leaves an intriguing question
1707
  - Creates a sense of wonder
1708
  - Maintains some mystery
1709
- Maximum 2 sentences.
1710
- """,
1711
  "Lesson Learned": """
1712
  Create a final sentence that:
1713
  - Shows what was learned
1714
  - Provides a moral lesson
1715
  - Connects to the story's events
1716
- Maximum 2 sentences.
1717
- """,
1718
  "Surprise Ending": """
1719
  Create a final twist ending that:
1720
  - Provides an unexpected but logical conclusion
1721
  - Connects to previous story elements
1722
  - Creates a satisfying surprise
1723
- Maximum 2 sentences.
1724
- """
1725
  }
1726
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1727
  response = client.chat.completions.create(
1728
- model="gpt-4",
1729
  messages=[
1730
  {
1731
  "role": "system",
1732
  "content": f"""
1733
- You are a master storyteller creating the final ending.
1734
  {ending_prompts[ending_type]}
 
 
 
1735
  This must be the absolute final sentence(s) of the story.
1736
  Make it conclusive and satisfying.
1737
  """
@@ -1741,8 +1784,8 @@ def generate_final_ending(story: List[dict], ending_type: str) -> str:
1741
  "content": f"Story context:\n{story_summary}\n\nCreate the final ending:"
1742
  }
1743
  ],
1744
- max_tokens=100,
1745
- temperature=0.7
1746
  )
1747
 
1748
  return response.choices[0].message.content.strip()
@@ -1751,7 +1794,8 @@ def generate_final_ending(story: List[dict], ending_type: str) -> str:
1751
  logging.error(f"Error generating final ending: {str(e)}")
1752
  return "And so, the story came to an end."
1753
 
1754
- def generate_ending_continuation(text: str, ending_type: str, remaining_sentences: int) -> str:
 
1755
  """Generate AI continuation focusing on story conclusion"""
1756
  try:
1757
  ending_prompts = {
@@ -1789,6 +1833,52 @@ def generate_ending_continuation(text: str, ending_type: str, remaining_sentence
1789
  """
1790
  }
1791
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1792
  response = client.chat.completions.create(
1793
  model="gpt-4o-mini",
1794
  messages=[
@@ -1797,21 +1887,22 @@ def generate_ending_continuation(text: str, ending_type: str, remaining_sentence
1797
  "content": f"""
1798
  {ending_prompts[ending_type]}
1799
 
 
 
1800
  Additional Rules:
1801
  - You have {remaining_sentences} sentences left to conclude the story.
1802
  - Each response should be maximum 2 sentences.
1803
  - Build towards the finale naturally.
1804
  - Ensure coherence with previous story events.
1805
- - Indicate awareness of the remaining sentences.
1806
  """
1807
  },
1808
  {
1809
  "role": "user",
1810
- "content": f"Continue and work towards ending this story: {text}"
1811
  }
1812
  ],
1813
- max_tokens=100,
1814
- temperature=0.7
1815
  )
1816
 
1817
  return response.choices[0].message.content.strip()
@@ -1820,7 +1911,6 @@ def generate_ending_continuation(text: str, ending_type: str, remaining_sentence
1820
  logging.error(f"Error generating ending continuation: {str(e)}")
1821
  return "The story moved towards its conclusion..."
1822
 
1823
-
1824
  def complete_story():
1825
  """Handle story completion and celebration"""
1826
  st.balloons() # แสดงเอฟเฟคฉลอง
 
752
  }
753
 
754
  try:
755
+ # Get recent story context (last 5 entries for more coherence)
756
  story_context = '\n'.join([
757
+ entry['content'] for entry in st.session_state.story[-5:]
758
  ]) if st.session_state.story else "Story just started"
759
 
760
  # Create prompt
 
817
  logging.error(f"Error generating story continuation: {str(e)}")
818
  return "I'm having trouble continuing the story. Please try again."
819
 
820
+
821
  def generate_dynamic_story_starter(theme_id: str, level: str) -> Dict[str, str]:
822
  """
823
  Dynamically generate a story starter based on theme and level.
 
1647
  ai_response = generate_ending_continuation(
1648
  text,
1649
  ending_type=st.session_state.ending_type,
1650
+ remaining_sentences=remaining,
1651
+ level=st.session_state.level
1652
  )
1653
 
1654
  # Add AI response
 
1666
  # Generate final ending
1667
  final_response = generate_final_ending(
1668
  st.session_state.story,
1669
+ st.session_state.ending_type,
1670
+ level=st.session_state.level
1671
  )
1672
 
1673
  # Add final AI response
 
1684
  # Clear input and rerun
1685
  st.session_state.text_input = ""
1686
  st.session_state.clear_input = True
1687
+ st.rerun()
1688
 
1689
  except Exception as e:
1690
  logging.error(f"Error in ending mode: {str(e)}")
1691
  st.error("เกิดข้อผิดพลาดในโหมดจบเรื่อง กรุณาลองใหม่อีกครั้ง")
1692
 
1693
+
1694
+ def generate_final_ending(story: List[dict], ending_type: str, level: str) -> str:
1695
  """Generate the final ending sentence based on the story and chosen ending type"""
1696
  try:
1697
  # Create a comprehensive prompt for the final ending
 
1703
  - Brings joy and satisfaction
1704
  - Resolves the main story elements
1705
  - Ends on a positive note
1706
+ """,
 
1707
  "Mysterious Ending": """
1708
  Create a final mysterious ending sentence that:
1709
  - Leaves an intriguing question
1710
  - Creates a sense of wonder
1711
  - Maintains some mystery
1712
+ """,
 
1713
  "Lesson Learned": """
1714
  Create a final sentence that:
1715
  - Shows what was learned
1716
  - Provides a moral lesson
1717
  - Connects to the story's events
1718
+ """,
 
1719
  "Surprise Ending": """
1720
  Create a final twist ending that:
1721
  - Provides an unexpected but logical conclusion
1722
  - Connects to previous story elements
1723
  - Creates a satisfying surprise
1724
+ """
 
1725
  }
1726
 
1727
+ level_context = {
1728
+ 'Beginner': {
1729
+ 'instructions': """
1730
+ Additional Guidelines:
1731
+ - Use only 1-2 VERY simple sentences
1732
+ - Use Present Simple Tense only
1733
+ - Basic vocabulary
1734
+ - 5-7 words per sentence maximum
1735
+ - Focus on clear, basic responses
1736
+ """,
1737
+ 'max_tokens': 30,
1738
+ 'temperature': 0.6
1739
+ },
1740
+ 'Intermediate': {
1741
+ 'instructions': """
1742
+ Additional Guidelines:
1743
+ - Use exactly 2 sentences maximum
1744
+ - Can use Present or Past Tense
1745
+ - Keep each sentence under 12 words
1746
+ - Grade-appropriate vocabulary
1747
+ - Add simple descriptions but stay concise
1748
+ """,
1749
+ 'max_tokens': 40,
1750
+ 'temperature': 0.7
1751
+ },
1752
+ 'Advanced': {
1753
+ 'instructions': """
1754
+ Additional Guidelines:
1755
+ - Use 2-3 sentences maximum
1756
+ - Various tenses allowed
1757
+ - Natural sentence length but keep overall response concise
1758
+ - More sophisticated vocabulary and structures
1759
+ - Create engaging responses that encourage creative continuation
1760
+ """,
1761
+ 'max_tokens': 50,
1762
+ 'temperature': 0.8
1763
+ }
1764
+ }
1765
+
1766
+ level_settings = level_context[level]
1767
+
1768
  response = client.chat.completions.create(
1769
+ model="gpt-4o-mini",
1770
  messages=[
1771
  {
1772
  "role": "system",
1773
  "content": f"""
 
1774
  {ending_prompts[ending_type]}
1775
+
1776
+ {level_settings['instructions']}
1777
+
1778
  This must be the absolute final sentence(s) of the story.
1779
  Make it conclusive and satisfying.
1780
  """
 
1784
  "content": f"Story context:\n{story_summary}\n\nCreate the final ending:"
1785
  }
1786
  ],
1787
+ max_tokens=level_settings['max_tokens'],
1788
+ temperature=level_settings['temperature']
1789
  )
1790
 
1791
  return response.choices[0].message.content.strip()
 
1794
  logging.error(f"Error generating final ending: {str(e)}")
1795
  return "And so, the story came to an end."
1796
 
1797
+
1798
+ def generate_ending_continuation(text: str, ending_type: str, remaining_sentences: int, level: str) -> str:
1799
  """Generate AI continuation focusing on story conclusion"""
1800
  try:
1801
  ending_prompts = {
 
1833
  """
1834
  }
1835
 
1836
+ level_context = {
1837
+ 'Beginner': {
1838
+ 'instructions': """
1839
+ Additional Guidelines:
1840
+ - Use only 1-2 VERY simple sentences
1841
+ - Use Present Simple Tense only
1842
+ - Basic vocabulary
1843
+ - 5-7 words per sentence maximum
1844
+ - Focus on clear, basic responses
1845
+ """,
1846
+ 'max_tokens': 30,
1847
+ 'temperature': 0.6
1848
+ },
1849
+ 'Intermediate': {
1850
+ 'instructions': """
1851
+ Additional Guidelines:
1852
+ - Use exactly 2 sentences maximum
1853
+ - Can use Present or Past Tense
1854
+ - Keep each sentence under 12 words
1855
+ - Grade-appropriate vocabulary
1856
+ - Add simple descriptions but stay concise
1857
+ """,
1858
+ 'max_tokens': 40,
1859
+ 'temperature': 0.7
1860
+ },
1861
+ 'Advanced': {
1862
+ 'instructions': """
1863
+ Additional Guidelines:
1864
+ - Use 2-3 sentences maximum
1865
+ - Various tenses allowed
1866
+ - Natural sentence length but keep overall response concise
1867
+ - More sophisticated vocabulary and structures
1868
+ - Create engaging responses that encourage creative continuation
1869
+ """,
1870
+ 'max_tokens': 50,
1871
+ 'temperature': 0.8
1872
+ }
1873
+ }
1874
+
1875
+ # Get recent story context
1876
+ story_context = '\n'.join([
1877
+ entry['content'] for entry in st.session_state.story[-5:]
1878
+ ]) if st.session_state.story else "Story just started"
1879
+
1880
+ level_settings = level_context[level]
1881
+
1882
  response = client.chat.completions.create(
1883
  model="gpt-4o-mini",
1884
  messages=[
 
1887
  "content": f"""
1888
  {ending_prompts[ending_type]}
1889
 
1890
+ {level_settings['instructions']}
1891
+
1892
  Additional Rules:
1893
  - You have {remaining_sentences} sentences left to conclude the story.
1894
  - Each response should be maximum 2 sentences.
1895
  - Build towards the finale naturally.
1896
  - Ensure coherence with previous story events.
 
1897
  """
1898
  },
1899
  {
1900
  "role": "user",
1901
+ "content": f"Story context:\n{story_context}\nStudent's input:\n{text}\nContinue and work towards ending this story:"
1902
  }
1903
  ],
1904
+ max_tokens=level_settings['max_tokens'],
1905
+ temperature=level_settings['temperature']
1906
  )
1907
 
1908
  return response.choices[0].message.content.strip()
 
1911
  logging.error(f"Error generating ending continuation: {str(e)}")
1912
  return "The story moved towards its conclusion..."
1913
 
 
1914
  def complete_story():
1915
  """Handle story completion and celebration"""
1916
  st.balloons() # แสดงเอฟเฟคฉลอง