import os import json # import langchain libraries from langchain import hub from langchain_groq import ChatGroq from langchain_core.prompts import ChatPromptTemplate from langchain.agents import Tool from langchain_core.prompts import PromptTemplate from langchain.chains.combine_documents import create_stuff_documents_chain from langchain_core.prompts import ChatPromptTemplate import gradio as gr import time from langchain_community.tools.tavily_search import TavilySearchResults import os import logging import requests from bs4 import BeautifulSoup from langchain_text_splitters import CharacterTextSplitter from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.schema import Document from youtube_transcript_api import YouTubeTranscriptApi, NoTranscriptFound from youtube_transcript_api.formatters import TextFormatter from youtube_transcript_api._errors import TranscriptsDisabled from serpapi import GoogleSearch import requests from langchain.agents import AgentExecutor, create_tool_calling_agent from langchain_core.prompts import ChatPromptTemplate from langchain.agents import Tool from langchain import hub from langchain.agents import AgentExecutor, create_structured_chat_agent from langchain_community.tools import DuckDuckGoSearchRun from duckduckgo_search import DDGS os.environ['SERPAPI_API_KEY']=os.getenv('serp') from langchain_community.utilities import SerpAPIWrapper # search = SerpAPIWrapper() # from google.colab import userdata # groq_api_key = userdata.get('GROQ_API_KEY') # api_key = userdata.get('twelvelabs') # os.environ["TAVILY_API_KEY"] = userdata.get('tavily') os.environ["TAVILY_API_KEY"] = os.getenv('tavily') groq_api_key = os.getenv('groq') api_key = os.getenv('twelvelabs') llm = ChatGroq( api_key=groq_api_key, model="llama3-8b-8192", max_tokens = 8000, # model = 'gemma-7b-it', temperature = 0 # model = 'mixtral-8x7B-32768' ) llamaver = ChatGroq( api_key=groq_api_key, model="llama-3.1-70b-versatile", max_tokens = 5000, temperature = 0) llmgemma = ChatGroq( api_key=groq_api_key, max_tokens = 8000, model = 'gemma2-9b-it', temperature = 0) mixtral = ChatGroq( api_key=groq_api_key, max_tokens = 5000, temperature = 0, model = 'mixtral-8x7B-32768') llama70 = ChatGroq( api_key=groq_api_key, model="llama3-70b-8192", max_tokens = 5000, temperature = 0) llmtool1= ChatGroq( api_key=groq_api_key, model="llama3-groq-70b-8192-tool-use-preview", max_tokens = 8000, # model = 'gemma-7b-it', temperature = 0 # model = 'mixtral-8x7B-32768' ) llmtool2= ChatGroq( api_key=groq_api_key, model="llama3-groq-8b-8192-tool-use-preview", max_tokens = 8000, # model = 'gemma-7b-it', temperature = 0 # model = 'mixtral-8x7B-32768' ) video_ids = ["6691bec83ca9a432304de035","6691bec83ca9a432304de035", "66936fd73ca9a432304de0e9", "6695a8bf3ca9a432304de1dd", "6695a8e03ca9a432304de1de", "6695a8ef3ca9a432304de1df", "6695a8f33ca9a432304de1e0"] video_ids2 = ["66a2f1e53ca9a432304dfc9f","66a2f2083ca9a432304dfca0", "66a2f22d3ca9a432304dfca1","66a2f2343ca9a432304dfca2", "66a2f24b3ca9a432304dfca3"] video_urls = ['https://www.youtube.com/watch?v=i2Cf6TjIiRA - Tamil Navigation', 'https://www.youtube.com/watch?v=xaWBeDasOOY - imax media', 'https://youtu.be/XCMigwdY0kI?si=Y1py32y6yU2fMR90 - shiva rose', 'https://youtu.be/0p2tKx0Ds7k?si=zjYhxyWIEuVdT0qj - Folks On Wheels', 'https://youtu.be/GZQ3rH_LJ78?si=GLJ14N712cu6etMK - Flower Milk Studio', 'https://youtu.be/3YGRt2irx9Q?si=skJhaVOZP4fIMrB0 - Kathaigal 1000'] video_urls2 = ["https://www.youtube.com/watch?v=eVFMDMpY36o - Before your trip", "https://www.youtube.com/watch?v=zhjpfZPDIZM - Jammmy Vlogs", "https://www.youtube.com/watch?v=zH-5UxiY6kA - Elena Taber", "https://www.youtube.com/watch?v=0JCGDm9NqzI - paddy doyle", "https://www.youtube.com/watch?v=eREftfTRsaQ - Island hopper tv"] video_authors = ['Tamil Navigation', 'imax media', 'shiva rose', 'Folks On Wheels', 'Flower Milk Studio', 'Kathaigal 1000'] # Variables BASE_URL = "https://api.twelvelabs.io/v1.2" def vlog_summarize(video_ids,destination): response2=[] for video_id in video_ids: data = {"video_id": video_id, "type": "summary"} resp = requests.post(f"{BASE_URL}/summarize", json=data, headers={"x-api-key": api_key}) data = resp.content.decode('utf-8') content = json.loads(data) # content = {'summary':"This tourist destination is a great place to visit"} vlog = llm.invoke(f''' You are an expert travel assistant. Given travel information, you can provide expert advice for new travellers.\ You will be given information with regard to some destination through various Youtube VLOG summaries. These summaries are all based on vloggers youtube videos pertaining to a single destination.\ YOu need to summarize them and provide a comprehensive advice based ONLY on the context provided below. YOu should not add any additional information.\ Your response should preferably be an essay and not bullet points unless otherwise necessary.\ destination = {destination} context = {content}.\ ''') response2.append(vlog.content) return response2 ############# to disable for test dest1 = 'Kondarangi Hills, Keeranur, Tamil Nadu' response2 = vlog_summarize(video_ids,dest1) dest2 = 'Seoul, South Korea' response3 = vlog_summarize(video_ids2,dest2) # ############3 # summary1 = [response2[0]['summary'],response2[1]['summary'],response2[2]['summary'], # response2[3]['summary'],response2[4]['summary'],response2[5]['summary']] # summary2 = [response3[0]['summary'],response3[1]['summary'],response3[2]['summary'], # response3[3]['summary'],response3[4]['summary']] # vlog = llm2.invoke(f''' You are an expert travel assistant. Given travel information, you can provide expert advice for new travellers to the SPECIFIED DESTINATION place.\ # You will be given information with regard to a through various summaries. These summaries are all based on vloggers youtube videos pertaining to a single destination.\ # YOu need to summarize them and provide a comprehensive advice based ONLY on the context provided below. YOu should not add any additional information.\ # Your response should be an essay and not bullet points unless otherwise necessary.\ # destination is {destination}.\ # context = {response2[0]['summary']}''') def vlogsumm(summary,destination,llm): vlog = llm.invoke(f''' You are an expert travel assistant. Given travel information, you can provide expert advice for new travellers.\ You will be given travel advice summary based on vloggers' youtube videos pertaining to a particular travel destination.\ You need to create a concise and comprehensive summary based ONLY on the context provided below. YOu should not add any additional information.\ Your response should preferably be an essay and not bullet points unless otherwise necessary.\ destination = {destination} context = {summary}.\ ''') vlogsummary = vlog.content return vlogsummary ###############to disable for test vlogsummary1 = vlogsumm(response2,dest1,llm) vlogsummary2 = vlogsumm(response3,dest2,llama70) ################## from langchain_community.document_loaders import WebBaseLoader # def get_docs(destination): # tool = TavilySearchResults(max_results=5) # resp =tool.invoke({"query": f"Tell me about tourist destination place called: {destination}"}) # urls = [result['url'] for result in resp] # essay = llamaver.invoke(f"You are a great travel advisor. Write an insightful and helpful essay for a traveller who plans to visit {destination}") # essaydoc = Document(page_content=essay) # docs=[] # docs.extend(essaydoc) # for url in urls: # if "youtube.com" not in url: # loader = WebBaseLoader(url) # try: # docs1 = loader.load() # docs.extend(docs1) # except Exception: # pass # return docs def get_docs(destination): tool = TavilySearchResults(max_results=5) resp =tool.invoke({"query": f"Tell me about tourist destination place called: {destination}"}) urls = [result['url'] for result in resp] print("urls ",urls) essay = llamaver.invoke(f"You are a great travel advisor. Write an insightful and helpful essay for a traveller who plans to visit {destination}") essaydoc = Document(page_content=essay.content) docs=[] docs.append(essaydoc) for url in urls: if "youtube.com" not in url: loader = WebBaseLoader(url) try: docs1 = loader.load() docs.extend(docs1) except Exception: pass print("docs created") return docs from langchain import hub from langchain.chains.combine_documents.stuff import StuffDocumentsChain from langchain.chains.llm import LLMChain from langchain_core.prompts import PromptTemplate from langchain.chains import MapReduceDocumentsChain, ReduceDocumentsChain from langchain_text_splitters import CharacterTextSplitter from duckduckgo_search import DDGS def get_blogsummary(docs): # Map map_template = """The following is a set of documents. \ {docs}. \ Provide a summary of each document. If the content is irrelevant, ignore it and just add a line "not relevant content" as summary instead of the content.\ summary:""" map_prompt = PromptTemplate.from_template(map_template) map_chain = LLMChain(llm=llm, prompt=map_prompt) # Reduce reduce_template = """The following is set of summaries:\ {docs}.\ Take these and distill it into a final, consolidated summary / travel advisory for the travel destination. \ The summary should be helpful for anybody to know everything about the place and plan his travel.\ NOTE: if there is irrelevant content, simply ignore those contents, consider the rest. If none of the content \ is relevant to the destination travel advice, then say some thing like "Proper Content Not Available" and do not add any other response, since \ this could be due to youtube audio / transcripts being not transcribed properly. \ Helpful Answer:""" reduce_prompt = PromptTemplate.from_template(reduce_template) # Note we can also get this from the prompt hub, as noted above # reduce_prompt = hub.pull("rlm/reduce-prompt") # Run chain reduce_chain = LLMChain(llm=llm, prompt=reduce_prompt) # Takes a list of documents, combines them into a single string, and passes this to an LLMChain combine_documents_chain = StuffDocumentsChain( llm_chain=reduce_chain, document_variable_name="docs" ) # Combines and iteratively reduces the mapped documents reduce_documents_chain = ReduceDocumentsChain( # This is final chain that is called. combine_documents_chain=combine_documents_chain, # If documents exceed context for `StuffDocumentsChain` collapse_documents_chain=combine_documents_chain, # The maximum number of tokens to group documents into. token_max=4000, ) # Combining documents by mapping a chain over them, then combining results map_reduce_chain = MapReduceDocumentsChain( # Map chain llm_chain=map_chain, # Reduce chain reduce_documents_chain=reduce_documents_chain, # The variable name in the llm_chain to put the documents in document_variable_name="docs", # Return the results of the map steps in the output return_intermediate_steps=True, ) text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder( chunk_size=1000, chunk_overlap=0 ) split_docs = text_splitter.split_documents(docs) print("docs splitted") result = map_reduce_chain.invoke(split_docs) print("summary results obtained") return result["output_text"] def get_transcriptsummary(docs): # Map map_template = """The following is a set of documents. \ {docs}. \ Provide a summary of each document. If the content is irrelevant, ignore it and just add a line "not relevant content" as summary instead of the content.\ summary:""" map_prompt = PromptTemplate.from_template(map_template) map_chain = LLMChain(llm=llm, prompt=map_prompt) # Reduce reduce_template = """The following is set of summaries:\ {docs}.\ Take these and distill it into a final, consolidated summary - it should be a nice insightful essay and not in bullet points form.\ Note that this summary need not be a travel advisory plan as travel advisory plan is given in this application through another function.\ This summary is meant to gather any SPECIAL USEFUL INSIGHTS from YOUTUBE VLOG TRANSCRIPTS. \ Becuase such information may not be available in blogs on the travel destination or in other websites. \ Hence, there is no need to give general travel plan. But it is enough if the summary focuses on \ any useful insights shared by the vlogger as transcribed in the transcript summaries.\ NOTE: if there is irrelevant content, simply ignore those contents, consider the rest. If none of the content \ is relevant to the destination travel advice, then say some thing like "Proper Content Not Available" and do not add any other response, since \ this could be due to youtube audio / transcripts being not transcribed properly. \ Helpful and Insightful summarized essay:""" reduce_prompt = PromptTemplate.from_template(reduce_template) # Note we can also get this from the prompt hub, as noted above # reduce_prompt = hub.pull("rlm/reduce-prompt") # Run chain reduce_chain = LLMChain(llm=llm, prompt=reduce_prompt) # Takes a list of documents, combines them into a single string, and passes this to an LLMChain combine_documents_chain = StuffDocumentsChain( llm_chain=reduce_chain, document_variable_name="docs" ) # Combines and iteratively reduces the mapped documents reduce_documents_chain = ReduceDocumentsChain( # This is final chain that is called. combine_documents_chain=combine_documents_chain, # If documents exceed context for `StuffDocumentsChain` collapse_documents_chain=combine_documents_chain, # The maximum number of tokens to group documents into. token_max=4000, ) # Combining documents by mapping a chain over them, then combining results map_reduce_chain = MapReduceDocumentsChain( # Map chain llm_chain=map_chain, # Reduce chain reduce_documents_chain=reduce_documents_chain, # The variable name in the llm_chain to put the documents in document_variable_name="docs", # Return the results of the map steps in the output return_intermediate_steps=True, ) text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder( chunk_size=1000, chunk_overlap=0 ) split_docs = text_splitter.split_documents(docs) result = map_reduce_chain.invoke(split_docs) return result["output_text"] def get_summary(destination,vlogsummary): docs = get_docs(destination) print("blog docs obtained") if vlogsummary: vlog_doc = Document(page_content=vlogsummary) docs.append(vlog_doc) summary = get_blogsummary(docs) return summary def vlog_queryresponse(prompt,video_ids, destination): response1=[] prompt = prompt + ''' Please note: This query is based on video content. \ Your answer shall be based on vlog video context given.\ You shall not add any information on your own.\ Also, Do not start the response with salutations, greetings etc. Just provide answers alone! ''' for video in video_ids: data = { "prompt": prompt, "video_id": video, "temperature": 0 } # Send request resp = requests.post(f"{BASE_URL}/generate", json=data, headers={"x-api-key": api_key}) data = resp.content.decode('utf-8') # Parse the JSON string into a dictionary content = json.loads(data) response1.append(content) # content = {'data':"This tourist destination is a quite risky adventure"} # response1.append(content) if 'Kondarangi Hills, Keeranur, Tamil Nadu' in destination: response_summary = [response1[0]['data'],response1[1]['data'],response1[2]['data'],response1[3]['data'],response1[4]['data'],response1[5]['data'],response1[6]['data']] elif 'Seoul, South Korea' in destination: response_summary = [response1[0]['data'],response1[1]['data'],response1[2]['data'],response1[3]['data'],response1[4]['data']] vlog = llm.invoke(f'''You are an expert travel assistant and summarizer. A tourist has asked a question regarding a tourist destination. \ The answer to that question has already been extracted from the VLOGs of many vloggers who posted their experience in Youtube.\ These answers are provided as context below. \ your task is to summarize these information given below. \ IMPORTANT NOTE: You should ONLY summarize and SHOULD NOT ADD any information on your own. \ Do not start the response with salutations, greetings etc. Just provide answers alone! \ The context is {response_summary}.\ Your summary should be concise, very insightful and useful to the traveller and in the paragraph format, not in bullet points.\ ''') vlogcontent = vlog.content return vlogcontent #####################3to disable for test destination1 = 'Kondarangi Hills, Keeranur, Tamil Nadu' results_kondarangi = get_summary(destination1,vlogsummary1) destination2 = 'Seoul, South Korea' results_seoul = get_summary(destination2,vlogsummary2) #########################3 def format_list(my_list): return '\n'.join(map(str, my_list)) ######################################################### def get_youtube_video_id(url): # Extract the video ID from the YouTube URL video_id = None if "youtube.com/watch?v=" in url: video_id = url.split("v=")[1] elif "youtu.be/" in url: video_id = url.split("/")[-1] return video_id def get_youtube_transcript(url): video_id = get_youtube_video_id(url) if not video_id: return None try: transcript_list = YouTubeTranscriptApi.list_transcripts(video_id) transcript = None # Try to find an English transcript first try: transcript = transcript_list.find_transcript(['en']) except NoTranscriptFound: # If no English transcript is found, use the first available transcript transcript = transcript_list.find_generated_transcript([trn.language_code for trn in transcript_list]) formatter = TextFormatter() return formatter.format_transcript(transcript.fetch()) except Exception as e: # Silently skip videos without transcripts print(f"Error fetching transcript for video {url}") return None def get_transcript_docs(destination): tool = TavilySearchResults(max_results=20) resp = tool.invoke({"query": f"Get me ONLY YOUTUBE URLs containing VLOGs (videos) pertaining to this travel destination location: {destination}"}) urls = [result['url'] for result in resp] docs = [] c=0 for url in urls: if c==10: break if "youtube.com" in url or "youtu.be" in url: print(url) transcript = get_youtube_transcript(url) if transcript: docs.append(transcript) c+=1 transcripts = [] for content in docs: doc = Document(page_content=content) transcripts.append(doc) return transcripts ################################################################# # Function to fetch image URL from SerpApi def get_image_url(destination): with DDGS() as ddgs: search_results = ddgs.images(destination, max_results=1) search_results_list = list(search_results) if search_results_list: image_url = search_results_list[0]['image'] return image_url else: return None # def get_image_url(destination): # api_key = "kkknbvvc" # search = GoogleSearch({"q": destination, "tbm": "isch", "api_key": api_key}) # results = search.get_dict() # try: # image_url1 = results["images_results"][0]["original"] # except IndexError: # image_url1 = None # return image_url1 def get_traveladvisory(origin, destination,prompt,llm): search=DuckDuckGoSearchRun() tools=[ Tool( name="DuckDuckgo search", func=search.run, description=f"Use this tool for for web search" ), ] prompt1 = hub.pull("hwchase17/structured-chat-agent") # Construct the Tools agent agent = create_structured_chat_agent(llm, tools, prompt1) try: # Create an agent executor by passing in the agent and tools agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True,handle_parsing_errors=True) response = agent_executor.invoke({"input": f'''{prompt}'''}) print("response obtained") return response['output'] except Exception as e: print(f"An error occurred: {str(e)}") ########################################################################################## ########################################################################################## # Functions called by gradio def travel_advisory(origin, selection, custom_input,days, purpose): if selection == "Enter": destination = custom_input else: destination = selection from datetime import datetime formatted_date = datetime.now().strftime("%d") + "th "+datetime.now().strftime("%B, %Y").replace(" 0", "") weather_pr = f'''You are an expert tourist advisor. For this question, You should give concise answer in few lines to the prompt asked.\ A person wants to visit the tourist location {destination} where he will spend some time / days experiencing the tourist place.\ He travels from {origin}. The advice you will give now is whether the climate and weather conditions are favorable at {destination}\ location at present date {formatted_date} and for the next one week from now.\ For this you need to know what is the weather conditions \ at the destination and the forecast for next week. You have got a tool available which will search internet for the current weather conditions\ at the location. While using the tool you should ensure that it fetches the current climate conditions like weather there is flood, natural disaster etc.\ you should also read current news items pertaining to that location to know the weather situation there like floods, natural disaster etc.\ destination = {destination}''' politics_pr = f'''You are an expert tourist advisor. For this question, You should give concise answer in few lines to the prompt asked.\ A person wants to visit the tourist location {destination} where he will spend some time / days experiencing the tourist place. He travels from {origin}.\ You need to give travel advice with regard to the location. The advice you will give now is with regard to political climate. Is there any state, local politics related problems at the {destination} location?.\ For example, there could be strikes affecting public transport, there could be political violence etc. You have got a tool available which will search internet\ to analyze the situation there. For example, you can read the latest new pertaining to the destination location to know whether there is any adverse political climate\ that could affect your travel plans there.\ destination = {destination}''' health_pr = f'''You are an expert tourist advisor. For this question, You should give concise answer in few lines to the prompt asked.\ A person wants to visit the tourist location {destination} where he will spend some time / days experiencing the tourist place.\ He travels from {origin}.\ You need to give travel advice with regard to the location. The advice you will give now is with regard to Health environment. \ Has there been any public health related problems at the {destination} location recently?.\ For example, some locations were affected by COVID related shutdowns in the past, some places due to dengue, NIPA virus etc.\ You have got a tool available which will search internet to analyze the 'health environment' situation there. \ For example, you can read the latest news pertaining to the destination location to provide health advisory.\ destination = {destination}''' general_pr = f'''You are an expert tourist advisor. Write a comprehensive tourist guide blog/essay of 3 paragraphs of length \ about the tourist destination {destination} which can be helpful for a traveller who plan to visit there.\ Use the tool given if necessary. \ He travels from {origin}\ destination = {destination}\ Number of days he will stay = {days}\ Purpose of visit = {purpose} ''' places_pr = f'''You are an expert tourist advisor. Give an expert advice on this question: \ What are the must see places i.e. top attractions, and interesting places to visit at tourist destination {destination}?\ Provide a concise overall advice in an insighful essay. Use the tool given if necessary.\ destination = {destination}''' itinerary_pr = f'''You are an expert tourist advisor. Given the destination to be visited: {destination}, and travel duration of {days}\ what is the effective travel itenerary do you suggest?. Basically, you need to give day's itinerary for each day - what places to visit,\ fist, next etc. Use the tool given, if necessary.\ destination = {destination}\ Number of days he will stay = {days}\ Purpose of visit = {purpose}''' image = get_image_url(destination) # print("image extracted") general = get_traveladvisory(origin,destination,general_pr,llm) print("general adv obtained") places = get_traveladvisory(origin,destination,places_pr,llama70) print("interesting places obtained") weather = get_traveladvisory(origin,destination,weather_pr,llm) print("weather obtained") politics = get_traveladvisory(origin,destination,politics_pr,llmgemma) print("political adv obtained") health = get_traveladvisory(origin,destination,health_pr,llm) print("health adv obtained") itinerary = get_traveladvisory(origin,destination,itinerary_pr,llm) print("itinerary obtained") return image,general, places, weather, politics, health, itinerary ################################################################ ########################################## def get_details(origin, selection,custom_input): if selection == "Enter": destination = custom_input else: destination = selection if destination == 'Kondarangi Hills, Keeranur, Tamil Nadu': results = results_kondarangi if destination == 'Seoul, South Korea': results = results_seoul flag = True indexed_destination = ['Kondarangi Hills, Keeranur, Tamil Nadu','Seoul, South Korea'] if destination not in indexed_destination: vlogsummary = None results = get_summary(destination,vlogsummary) flag = False distance = llama70.invoke(f'What is the distance between {origin} and {destination}. Do not start the response with salutations, greetings etc. Just provide answers alone!') mode = llama70.invoke(f'What is the best way to travel from {origin} to {destination}. Do not start the response with salutations, greetings etc. Just provide answers alone!') cost = llama70.invoke(f'What is the approximate cost of travel from {origin} to {destination}. Do not start the response with salutations, greetings etc. Just provide answers alone!') return distance.content, mode.content, cost.content,results def get_dummy(origin, selection,custom_input): if selection == "Enter": destination = custom_input else: destination = selection return destination,destination, destination, destination def get_vlog_details(selection,custom_input): if selection == "Enter": destination = custom_input else: destination = selection if destination == 'Kondarangi Hills, Keeranur, Tamil Nadu': vlog_url = format_list(video_urls) vlogcontent = vlogsummary1 elif destination == 'Seoul, South Korea': vlog_url = format_list(video_urls2) vlogcontent = vlogsummary2 else: vlog_url = 'Sorry, Being Demo app, VLOGS available only for and !' vlogcontent = 'Sorry, Being Demo app, VLOGS available only for and !' return vlog_url, vlogcontent def get_transcript_summary(selection,custom_input): if selection == "Enter": destination = custom_input else: destination = selection transcripts = get_transcript_docs(destination) transcript_summary = get_transcriptsummary(transcripts) return transcript_summary def vlog_query(prompt,selection,custom_input): if selection == "Enter": destination = custom_input else: destination = selection if 'Kondarangi Hills, Keeranur, Tamil Nadu' in destination: vlogcontent = vlog_queryresponse(prompt,video_ids,destination) elif 'Seoul, South Korea' in destination: vlogcontent = vlog_queryresponse(prompt,video_ids2,destination) else: vlogcontent = "Sorry, Being Demo app, VLOGS for above destination are not yet indexed - Try or !" return vlogcontent # Function to clear outputs def clear_outputs(): return None, '', '', '', '', '', '', '', '', '', '','','' def suggest_places(origin, category, distance, days, description): response = llamaver.invoke(f''' you are an expert travel assistant. \ You will be given some context based on which you have to suggest five travel places for the traveller who has not planned his destination.\ The context will have following information:\ 1. Nature of place he wants to visit like mountains, beach etc - {category}.\ 2. distance - radius of distance within which the tourist destination should be from {origin} - {distance}.\ 3. duration of stay he is planning - {days}.\ 4. Additional requirements in descriptive words - {description}.\ Based on the above, you have to give five tourist destination suggestions.\ ''') return response.content # Gradio app with gr.Blocks() as demo: # Set the global logging level to ERROR to suppress warnings logging.basicConfig(level=logging.ERROR) gr.Markdown("""

Trip Advisor with VLOG content!

""") gr.Markdown("

Powered by GROQ, Llama3, Pegasus, Langchain, Youtube, Duckduckgo-search

") with gr.Tabs(): # Tab 1: Travel Suggestions with gr.TabItem("Travel Suggestions"): gr.Markdown("""

Where do you want to go?!

""") gr.Markdown(""" This section is meant to give you some AI-based suggestions based on your choices!""") gr.Image("traveladvisory.jpg", width=500) origin1 = gr.Textbox(label='Enter Starting Place', value='Trichy') category_radio = gr.Radio( choices=[ "Nature and Adventure", "Cultural and Historical", "Spiritual and Religious", "Beach and Coastal", "Urban and Modern", "Countryside and Rural", "Wellness and Relaxation", "Entertainment and Theme Parks", "Culinary and Food Tourism" ], label="Select Place Category", value="Nature and Adventure" ) distance_radio = gr.Radio( choices=["Within 500 kms", "Within Country", "Outside Country"], label="Select Distance", value="Within 500 kms" ) days_radio = gr.Radio( choices=["Within 3 Days", "Seven Days", "Month and Above"], label="Select Duration", value="Within 3 Days" ) description_textbox = gr.Textbox( placeholder="Describe the kind of place you want to visit", label="Describe your tourist destination", value="I am planning for a very risky hill trekking experience, where many have not gone before!" ) output_box = gr.Markdown( label="Suggested Places", value="The suggested places will appear here..." ) submit_btn6 = gr.Button("Get Travel Suggestions!") submit_btn6.click( suggest_places, inputs=[origin1, category_radio, distance_radio, days_radio, description_textbox], outputs=output_box ) # Tab 2: Travel Tips with gr.TabItem("Travel Tips"): gr.Markdown("""

Know more about your destination!

""") gr.Markdown(""" This section is meant to give you AI tips for your tourist destination!""") origin = gr.Textbox(label='Enter Starting Place', value='Trichy') with gr.Row(): dropdown = gr.Dropdown(choices=["Kondarangi Hills, Keeranur, Tamil Nadu", "Seoul, South Korea", "Enter"], label="Select or Enter Destination", value="Seoul, South Korea") text_input = gr.Textbox(label="Enter destination", visible=False, value="Maui, Hawaii") with gr.Row(): days = gr.Textbox(label='Enter Duration in days', value= 5) purpose = gr.Textbox(label='Purpose of visit', value='General') def update_text_input(selected_option): return gr.update(visible=(selected_option == "Enter")) dropdown.change(fn=update_text_input, inputs=dropdown, outputs=text_input) with gr.Row(): submit_btn5 = gr.Button("Get AI Travel Tips!") reset_btn = gr.Button("Reset All") image = gr.Image(label='Travel Destination', interactive=False, width=500) gr.Markdown("""

General

""") essay = gr.Markdown(label="") gr.Markdown("""

Places to visit

""") places = gr.Markdown(label="") gr.Markdown("""

Suggested Itinerary

""") itinerary = gr.Markdown(label="") gr.Markdown("""

Current Weather

""") weather = gr.Markdown(label="") gr.Markdown("""

Political Climate

""") political = gr.Markdown(label="") gr.Markdown("""

Health Advisory

""") health = gr.Markdown(label="") submit_btn5.click( travel_advisory, inputs=[origin, dropdown, text_input,days, purpose], outputs=[image, essay, places, weather, political, health,itinerary] ) # Tab 3: General Content with gr.TabItem("General Content"): gr.Markdown("""

General Content

""") gr.Markdown(""" This section gives general advice pertaining to the tourist destination based on web search.""") gr.Image("traveltipimage.jpg", width=500) submit_btn1 = gr.Button("Get Trip Advice!") gr.Markdown("""

Distance

""") rdist = gr.Markdown(label="Distance") gr.Markdown("""

Mode of Travel

""") rmode = gr.Markdown(label="Mode of travel") gr.Markdown("""

General Advisory

""") rdescr = gr.Markdown(label="General Advisory") gr.Markdown("""

Approx. Cost Summary

""") rcost = gr.Markdown(label="Approx. Cost of travel") submit_btn1.click( get_details, inputs=[origin, dropdown, text_input], outputs=[rdist, rmode, rcost, rdescr] ) # Tab 4: VLOG Multimodal Summary with gr.TabItem("VLOG Multimodal"): gr.Markdown("""

VLOG Multimodal Video based Content

""") gr.Markdown(""" This section is based on multimodal VLOG content and uses the Pegasus Search Engine""") gr.Image("vlog.jpg", width=500) submit_btn2 = gr.Button("Get VLOG Multimodal Content Based Advice!") vlogs_url = gr.Textbox(label='VLOGs content indexed', interactive=False) gr.Markdown("""

VLOG Multimodal Response

""") vlog_info = gr.Markdown(label="VLOGs Advisory") submit_btn2.click( get_vlog_details, inputs=[dropdown, text_input], outputs=[vlogs_url, vlog_info] ) # Tab 5: VLOG Transcript Summary with gr.TabItem("VLOG Transcript"): gr.Markdown("""

VLOG Transcript based Advice

""") gr.Markdown(""" This section gives advice based on YouTube transcripts - helpful when VLOGs are not indexed!""") gr.Image("yt.jpg", width=500) submit_btn3 = gr.Button("Get VLOG Youtube Transcripts Based Advice!") transcriptsummary = gr.Markdown(label="VLOG Transcript Summary") submit_btn3.click( get_transcript_summary, inputs=[dropdown, text_input], outputs=[transcriptsummary] ) # Tab 6: VLOG Chat with gr.TabItem("VLOG Chat"): gr.Markdown("""

VLOG based Chat Response

""") gr.Markdown(""" In this section, you can query and get answers based on VLOG content!""") gr.Image("vlogchatjpg.jpg", width=500) vlogquery = gr.Textbox(label="Ask any query to vloggers!", value='What do vloggers say about this tourist destination?') submit_btn4 = gr.Button("Chat with VLOGs") vlogquery_info = gr.Markdown(label="VLOG query response") submit_btn4.click( vlog_query, inputs=[vlogquery, dropdown, text_input], outputs=[vlogquery_info] ) # # Reset button # with gr.TabItem("Reset"): # reset_btn.click( # clear_outputs, # inputs=None, # outputs=[image, essay, places, weather, political, health, rdist, rmode, rcost, rdescr, vlog_info, transcriptsummary, vlogquery_info] # ) demo.launch()