Advertisement
EdmundC

a.i.

Sep 21st, 2024 (edited)
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.53 KB | None | 0 0
  1. import aiohttp
  2. import asyncio
  3. import random
  4.  
  5. # Load words from the text files
  6. def read_words_from_file(filename):
  7.     with open(filename, 'r') as file:
  8.         words = file.read().splitlines()
  9.     return words
  10.  
  11. # Load words from the three text files
  12. chunk1_words = read_words_from_file('chunk1.txt')
  13. chunk2_words = read_words_from_file('chunk2.txt')
  14. chunk3_words = read_words_from_file('chunk3.txt')
  15.  
  16. # Combine all words into one pool
  17. word_pool = chunk1_words + chunk2_words + chunk3_words
  18.  
  19. # Cache for definitions to avoid repeated API calls
  20. definition_cache = {}
  21.  
  22. # Function to fetch definitions from the API
  23. async def fetch_definition(session, word):
  24.     if word in definition_cache:
  25.         return definition_cache[word]
  26.  
  27.     url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}"
  28.     try:
  29.         async with session.get(url) as response:
  30.             if response.status == 429:
  31.                 print(f"Rate limit exceeded for '{word}'. Waiting...")
  32.                 await asyncio.sleep(5)  # Wait for 5 seconds before retrying
  33.                 return await fetch_definition(session, word)  # Retry fetching the definition
  34.             response.raise_for_status()
  35.             definitions = await response.json()
  36.             definitions_list = [definition['meanings'][0]['definitions'][0]['definition'] for definition in definitions]
  37.             definition_cache[word] = definitions_list
  38.             return definitions_list
  39.     except Exception as e:
  40.         print(f"Error fetching definition for '{word}': {e}")
  41.         return []
  42.  
  43. # Function to compute semantic similarity using Jaccard index
  44. def are_definitions_similar(def1, def2):
  45.     words1 = set(def1.lower().split())
  46.     words2 = set(def2.lower().split())
  47.     intersection = len(words1.intersection(words2))
  48.     union = len(words1.union(words2))
  49.     return (intersection / union) > 0.5  # Adjustable threshold
  50.  
  51. # Function to find a suitable word based on definitions
  52. async def find_suitable_word(topics):
  53.     async with aiohttp.ClientSession() as session:
  54.         all_definitions = []
  55.         for topic in topics:
  56.             definitions = await fetch_definition(session, topic)
  57.             if definitions:
  58.                 all_definitions.extend(definitions)
  59.  
  60.         if not all_definitions:
  61.             return None, []
  62.  
  63.         for word in word_pool:
  64.             definitions = await fetch_definition(session, word)
  65.             if definitions:
  66.                 for def1 in all_definitions:
  67.                     for def2 in definitions:
  68.                         if are_definitions_similar(def1, def2):
  69.                             return word, definitions
  70.         return None, []
  71.  
  72. # Function to construct a grammatically correct sentence
  73. def construct_sentence(word, definitions):
  74.     return f"The word '{word}' can mean: {', '.join(definitions)}."
  75.  
  76. # Main AI conversation function
  77. async def ai_conversation(topic):
  78.     topics = topic.split()  # Split the topic into individual words
  79.     word, definitions = await find_suitable_word(topics)
  80.     if word:
  81.         return construct_sentence(word, definitions)
  82.     else:
  83.         return "AI: No suitable word found for the conversation."
  84.  
  85. # Main loop
  86. if __name__ == "__main__":
  87.     topic = input("Enter a topic for the AI conversation: ")
  88.  
  89.     async def main():
  90.         while True:
  91.             response = await ai_conversation(topic)
  92.             print(response)
  93.             cont = input("Continue the conversation? (yes/no): ")
  94.             if cont.lower() != 'yes':
  95.                 break
  96.  
  97.     asyncio.run(main())
  98.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement