jobanpreet123 commited on
Commit
2c20470
1 Parent(s): a578907

code changes done

Browse files
.env CHANGED
@@ -1 +1 @@
1
- cohere_api_key="CTx2vcy4vjHeGC77cGGQXrCCz4xZYxlnPyFWZqqe"
 
1
+ COHERE_API_KEY="CTx2vcy4vjHeGC77cGGQXrCCz4xZYxlnPyFWZqqe"
__pycache__/advance_post.cpython-310.pyc CHANGED
Binary files a/__pycache__/advance_post.cpython-310.pyc and b/__pycache__/advance_post.cpython-310.pyc differ
 
__pycache__/blog_post.cpython-310.pyc ADDED
Binary file (1.41 kB). View file
 
__pycache__/paraphrase_post.cpython-310.pyc CHANGED
Binary files a/__pycache__/paraphrase_post.cpython-310.pyc and b/__pycache__/paraphrase_post.cpython-310.pyc differ
 
__pycache__/scrap_post.cpython-310.pyc CHANGED
Binary files a/__pycache__/scrap_post.cpython-310.pyc and b/__pycache__/scrap_post.cpython-310.pyc differ
 
__pycache__/streaming_response.cpython-310.pyc ADDED
Binary file (795 Bytes). View file
 
advance_post.py CHANGED
@@ -4,11 +4,12 @@ from langchain.prompts import PromptTemplate
4
  from langchain_community.document_loaders import WebBaseLoader
5
  from langchain.prompts import ChatPromptTemplate
6
  from langchain_core.output_parsers import StrOutputParser
7
- import nest_asyncio
8
 
9
 
10
- def google_search(linkedin_post,model , google_api_key, search_engine_id , num_results_per_query=[3,2,1]):
11
 
 
 
12
  response_schemas = [
13
  ResponseSchema(name="questions", description="These are the top three relevant questions from the LinkedIn post" , type="list")]
14
  output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
@@ -28,10 +29,10 @@ def google_search(linkedin_post,model , google_api_key, search_engine_id , num_r
28
  )
29
 
30
  chain = prompt | model | output_parser
31
- result=chain.invoke({"post": linkedin_post})
32
  questions=result['questions']
33
  # print(questions)
34
-
35
  all_links = []
36
  for query, num_results in zip(questions, num_results_per_query):
37
  url = f"https://www.googleapis.com/customsearch/v1?key={google_api_key}&cx={search_engine_id}&q={query}&tbm=nws&num={num_results}"
@@ -42,32 +43,12 @@ def google_search(linkedin_post,model , google_api_key, search_engine_id , num_r
42
  all_links.extend(links)
43
 
44
 
45
- return all_links
46
-
47
 
48
- # nest_asyncio.apply()
49
- # def advanced_post(all_links ,model ,linkedinpost):
50
- # loader = WebBaseLoader(all_links,encoding="utf-8")
51
- # loader.requests_per_second = 1
52
- # docs = loader.load()
53
- # template="""You are a helpful linkedin post creator . You are provided with LinkedIn post and documents related to the post extracted from different articles from the internet.
54
- # Your task is to create a new linkedin post but content should be taken from the documents according to the semantic similarity of the post content with document content.
55
-
56
- # Linkedin post:{post}
57
- # Documents: {content}"""
58
-
59
- # prompt = ChatPromptTemplate.from_template(template)
60
- # chain= prompt | model | StrOutputParser()
61
- # result=chain.invoke({'post':linkedinpost , 'content':docs})
62
- # return result , docs
63
-
64
- nest_asyncio.apply()
65
- def advanced_post(all_links ,model ,linkedinpost):
66
  loader = WebBaseLoader(all_links,encoding="utf-8")
67
  loader.requests_per_second = 1
68
  docs = loader.load()
69
- template1="""You are provided with LinkedIn post and document which is related to the post . Your task is to extract the relevant information from the document which has similarity with LinkedIn post.
70
- Do not add LinkedIn Post content. It should only from document.
71
  Linkedin post:{post}
72
  Document: {content}"""
73
 
@@ -75,13 +56,11 @@ def advanced_post(all_links ,model ,linkedinpost):
75
  chain= prompt | model | StrOutputParser()
76
  relevant_content=""
77
  for i in docs:
78
- r=chain.invoke({'post':linkedinpost , 'content':i.page_content})
79
  relevant_content+=r
80
 
81
- template2="""You are provided with a document. Your task is to create a new LinkedIn post. Take content from the document only. Choose the topic of the post wisely. Do not add anything outside of the provided document content.
82
- Format should be professional .It should include topic , headings , key points , stickers and emojis.
83
-
84
- The length of the post should be between 400 to 500 words.
85
  Document: {content}"""
86
  prompt2 = ChatPromptTemplate.from_template(template2)
87
  chain2= prompt2 | model | StrOutputParser()
 
4
  from langchain_community.document_loaders import WebBaseLoader
5
  from langchain.prompts import ChatPromptTemplate
6
  from langchain_core.output_parsers import StrOutputParser
7
+ from scrap_post import scrappost
8
 
9
 
 
10
 
11
+ def google_search(url,model , google_api_key, search_engine_id , num_results_per_query=[3,2,1]):
12
+ post=scrappost(url)
13
  response_schemas = [
14
  ResponseSchema(name="questions", description="These are the top three relevant questions from the LinkedIn post" , type="list")]
15
  output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
 
29
  )
30
 
31
  chain = prompt | model | output_parser
32
+ result=chain.invoke({"post": post})
33
  questions=result['questions']
34
  # print(questions)
35
+
36
  all_links = []
37
  for query, num_results in zip(questions, num_results_per_query):
38
  url = f"https://www.googleapis.com/customsearch/v1?key={google_api_key}&cx={search_engine_id}&q={query}&tbm=nws&num={num_results}"
 
43
  all_links.extend(links)
44
 
45
 
 
 
46
 
47
+ # def advanced_post(all_links ,model ,post):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  loader = WebBaseLoader(all_links,encoding="utf-8")
49
  loader.requests_per_second = 1
50
  docs = loader.load()
51
+ template1="""Extract pertinent information from the provided document that aligns with the content of the LinkedIn post. Focus solely on the document to identify and highlight relevant details that mirror the themes or topics discussed in the post. Avoid incorporating any content from the LinkedIn post itself, ensuring that the extracted information complements and enhances the post's message.
 
52
  Linkedin post:{post}
53
  Document: {content}"""
54
 
 
56
  chain= prompt | model | StrOutputParser()
57
  relevant_content=""
58
  for i in docs:
59
+ r=chain.invoke({'post':post , 'content':i.page_content})
60
  relevant_content+=r
61
 
62
+ template2="""Utilizing the content from the provided document, craft a new LinkedIn post focusing on a carefully chosen topic. Ensure a professional format incorporating headings, key points, stickers, and emojis to enhance engagement. The post's length should not surpass 3000 characters, and all content must be derived solely from the document.
63
+ Strive to select a topic that resonates with the document's information and presents it in a compelling and informative manner.
 
 
64
  Document: {content}"""
65
  prompt2 = ChatPromptTemplate.from_template(template2)
66
  chain2= prompt2 | model | StrOutputParser()
app.py CHANGED
@@ -1,69 +1,74 @@
1
  import streamlit as st
2
  import re
3
  import openai
4
- from paraphrase_post import get_original_url , paraphrased_post
5
- from advance_post import google_search , advanced_post
6
  from langchain_community.chat_models import ChatOpenAI
7
  from langchain_cohere import ChatCohere
 
 
8
  # from langchain_nvidia_ai_endpoints import ChatNVIDIA
9
-
10
  #from langchain import HuggingFaceHub
11
 
12
 
13
- def main():
14
- st.title("LinkedIn Post Creator")
15
-
16
- # Initialize SessionState dictionary
17
- session_state = st.session_state
18
-
19
- if 'paraphrase' not in session_state:
20
- session_state.paraphrase = ""
21
- if 'keywords' not in session_state:
22
- session_state.keywords = ""
23
- if 'take_aways' not in session_state:
24
- session_state.take_aways = ""
25
- if 'highlights' not in session_state:
26
- session_state.highlights = ""
27
-
28
- if 'advancepost' not in session_state:
29
- session_state.advancepost = ""
30
-
31
- url = st.sidebar.text_input("Enter URL:", placeholder="Enter URL here...")
32
- option = st.sidebar.selectbox('Select Model:', ('GPT-4',"Cohere"))
33
- temperature= st.sidebar.select_slider(
34
- 'How much accurate post you want ?',
35
- options=['Less accuracy', 9, 8, 7, 6, 5,4,3 ,2,1,'High accuracy'])
36
- if temperature=='Less accuracy':
37
- temperature=10
38
- elif temperature=="High accuracy":
39
- temperature=0
40
- temperature=temperature/10
41
-
42
-
43
- if option=="GPT-4":
44
- api_key=st.sidebar.text_input("API Key:",placeholder="Enter OpenAI API Key...")
45
- if api_key:
46
- model=ChatOpenAI(model="gpt-4-turbo-preview" , temperature=temperature , api_key=api_key)
47
- elif option=="Cohere":
48
- api_key= st.sidebar.text_input("API Key:",placeholder="Enter Cohere API Key...")
49
- if api_key:
50
- model = ChatCohere(cohere_api_key=api_key , temperature = temperature , model = "command-r-plus")
51
- # elif option=="Mixtral-8x7b":
52
- # api_key=st.sidebar.text_input("API Key:",placeholder="Enter NVIDIA NIM API Key...")
53
- # if api_key:
54
- # model = ChatNVIDIA(model="mixtral_8x7b",api_key = api_key , temperature=temperature)
55
-
56
-
57
-
58
-
59
- # elif option=="Llama-3":
60
- # api_key=st.sidebar.text_input("API Key:",placeholder="Enter HuggingFace API Token...")
61
- # if api_key:
62
- # model=HuggingFaceHub(repo_id="mistralai/Mixtral-8x22B-Instruct-v0.1",huggingfacehub_api_token=api_key ,model_kwargs={"temperature":temperature})
63
-
64
-
65
-
66
-
 
 
 
 
67
  if st.sidebar.button("Submit"):
68
  if url:
69
  if api_key:
@@ -72,7 +77,7 @@ def main():
72
 
73
  if match:
74
  try:
75
- session_state.paraphrase, session_state.keywords, session_state.take_aways, session_state.highlights = paraphrased_post(url , model)
76
  except (openai.AuthenticationError) as e:
77
  st.sidebar.error("Enter your valid API key")
78
  else:
@@ -81,55 +86,100 @@ def main():
81
  st.sidebar.error("Please enter API Key")
82
  else:
83
  st.sidebar.error("Please enter url")
84
-
85
- # def stream_data():
86
- # import time
87
- # for word in session_state.paraphrase.split(" "):
88
- # yield word + " "
89
- # time.sleep(0.02)
90
-
91
-
92
- # st.write_stream(word +" ")
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- paraphrase_text=st.text_area("Generated LinkedIn post",value=session_state.paraphrase, height=400)
95
- # import pyperclip
96
- # if st.button('Copy'):
97
- # pyperclip.copy(paraphrase_text)
98
- # st.success('Text copied successfully!')
99
-
100
- if st.sidebar.toggle("Show Details") and session_state.keywords:
101
- st.write("Keywords:")
102
- for i, statement in enumerate(session_state.keywords, start=1):
103
- st.write(f"{i}. {statement}")
104
-
105
- st.write("Take Aways:")
106
- for i, statement in enumerate(session_state.take_aways, start=1):
107
- st.write(f"{i}. {statement}")
108
 
109
- st.write("Highlights:")
110
- for i, statement in enumerate(session_state.highlights, start=1):
111
- st.write(f"{i}. {statement}")
112
 
113
  #------------------------------------------------------------Advance LinkedIn post code below-----------------------------------------------------------------
114
-
115
- if st.sidebar.toggle("Advance LinkedIn Post"):
116
- google_api_key=st.sidebar.text_input("Google API Key:",placeholder="Enter Google Search API Key...")
117
- search_engine_id=st.sidebar.text_input("Search Engine ID:",placeholder="Enter Search Engine ID...")
118
- google_api_key = "AIzaSyABoOsfUbydc1AfVf2Zjto4MFWNgjLSJmY"
119
- search_engine_id = "243a392ba3dff442c"
120
- if st.sidebar.button("Generate Advance Post"):
121
- if google_api_key:
122
- if search_engine_id:
123
- all_links =google_search(session_state.paraphrase ,model , google_api_key,search_engine_id)
124
- session_state.advancepost = advanced_post(all_links ,model ,session_state.paraphrase)
125
- # if len(docs)==0:
126
- # st.sidebar.error("Please Check your both credentials carefully")
127
-
128
- else:
129
- st.sidebar.error("Please enter Search Engine ID")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  else:
131
- st.sidebar.error("Please enter Google API Key")
132
- advance_post=st.text_area("Advance LinkedIn post",value=session_state.advancepost, height=400)
 
 
133
 
134
 
135
  # if st.button('Copy Advanced Post'):
@@ -137,8 +187,8 @@ def main():
137
  # st.success('Text copied successfully!')
138
  #--------------------------------------------------------------------------------------------------------------------------------------------------------------
139
 
140
- if __name__ == "__main__":
141
- main()
142
 
143
 
144
 
 
1
  import streamlit as st
2
  import re
3
  import openai
4
+ from paraphrase_post import get_original_url , paraphrased_post
5
+ from advance_post import google_search
6
  from langchain_community.chat_models import ChatOpenAI
7
  from langchain_cohere import ChatCohere
8
+ from streaming_response import StreamHandler
9
+ from blog_post import post_from_content
10
  # from langchain_nvidia_ai_endpoints import ChatNVIDIA
 
11
  #from langchain import HuggingFaceHub
12
 
13
 
14
+ # def main():
15
+ st.title("LinkedIn Post Creator")
16
+
17
+ # Initialize SessionState dictionary
18
+ session_state = st.session_state
19
+
20
+ if 'paraphrase' not in session_state:
21
+ session_state.paraphrase = ""
22
+ if 'keywords' not in session_state:
23
+ session_state.keywords = ""
24
+ if 'take_aways' not in session_state:
25
+ session_state.take_aways = ""
26
+ if 'highlights' not in session_state:
27
+ session_state.highlights = ""
28
+
29
+ if 'advancepost' not in session_state:
30
+ session_state.advancepost = ""
31
+
32
+ # url = st.sidebar.text_input("Enter URL:", placeholder="Enter URL here...")
33
+ option = st.sidebar.selectbox('Select Model:', ('GPT-4',"Cohere"))
34
+ temperature= st.sidebar.select_slider(
35
+ 'How much accurate post you want ?',
36
+ options=['Less accuracy', 9, 8, 7, 6, 5,4,3 ,2,1,'High accuracy'])
37
+ if temperature=='Less accuracy':
38
+ temperature=10
39
+ elif temperature=="High accuracy":
40
+ temperature=0
41
+ temperature=temperature/10
42
+
43
+ # stream_handler = StreamHandler(st.empty())
44
+
45
+ if option=="GPT-4":
46
+ api_key=st.sidebar.text_input("API Key:",placeholder="Enter OpenAI API Key...")
47
+ if api_key:
48
+ model=ChatOpenAI(model="gpt-4-turbo-preview" , temperature=temperature , api_key=api_key)
49
+ elif option=="Cohere":
50
+ api_key= st.sidebar.text_input("API Key:",placeholder="Enter Cohere API Key...")
51
+ if api_key:
52
+ stream_handler = StreamHandler(st.empty())
53
+ model = ChatCohere(cohere_api_key=api_key,temperature=temperature , streaming=True, callbacks=[stream_handler])
54
+ #model = ChatCohere(cohere_api_key=api_key , temperature = temperature , model = "command-r-plus")
55
+ # elif option=="Mixtral-8x7b":
56
+ # api_key=st.sidebar.text_input("API Key:",placeholder="Enter NVIDIA NIM API Key...")
57
+ # if api_key:
58
+ # model = ChatNVIDIA(model="mixtral_8x7b",api_key = api_key , temperature=temperature)
59
+
60
+
61
+
62
+
63
+ # elif option=="Llama-3":
64
+ # api_key=st.sidebar.text_input("API Key:",placeholder="Enter HuggingFace API Token...")
65
+ # if api_key:
66
+ # model=HuggingFaceHub(repo_id="mistralai/Mixtral-8x22B-Instruct-v0.1",huggingfacehub_api_token=api_key ,model_kwargs={"temperature":temperature})
67
+
68
+
69
+
70
+ if st.sidebar.toggle("Normal LinkedIn Post"):
71
+ url = st.sidebar.text_input("Enter URL:", placeholder="Enter URL here...")
72
  if st.sidebar.button("Submit"):
73
  if url:
74
  if api_key:
 
77
 
78
  if match:
79
  try:
80
+ session_state.paraphrase = paraphrased_post(url , model)
81
  except (openai.AuthenticationError) as e:
82
  st.sidebar.error("Enter your valid API key")
83
  else:
 
86
  st.sidebar.error("Please enter API Key")
87
  else:
88
  st.sidebar.error("Please enter url")
89
+ from paraphrase_post import generate_details
90
+ if st.sidebar.button("Show Details"):
91
+ session_state.keywords =generate_details(session_state.paraphrase , model)
92
+
93
+
94
+
95
+ # paraphrase_text=st.text_area("Generated LinkedIn post",value=session_state.paraphrase, height=400)
96
+ # import pyperclip
97
+ # if st.button('Copy'):
98
+ # pyperclip.copy(paraphrase_text)
99
+ # st.success('Text copied successfully!')
100
+ # from paraphrase_post import extract_data
101
+ # # session_state.keywords , session_state.take_aways , session_state.highlights =extract_data(session_state.paraphrase , model)
102
+ # from paraphrase_post import generate_details
103
+ # if st.sidebar.button("Show Details"):
104
+ # session_state.keywords =generate_details(session_state.paraphrase , model)
105
+ # session_state.take_aways =generate_takeaways(session_state.paraphrase , model)
106
+ # session_state.highlights =generate_highlights(session_state.paraphrase , model)
107
+
108
+ # st.write("Keywords:")
109
+ # for i, statement in enumerate(session_state.keywords, start=1):
110
+ # st.write(f"{i}. {statement}")
111
 
112
+ # st.write("Take Aways:")
113
+ # for i, statement in enumerate(session_state.take_aways, start=1):
114
+ # st.write(f"{i}. {statement}")
 
 
 
 
 
 
 
 
 
 
 
115
 
116
+ # st.write("Highlights:")
117
+ # for i, statement in enumerate(session_state.highlights, start=1):
118
+ # st.write(f"{i}. {statement}")
119
 
120
  #------------------------------------------------------------Advance LinkedIn post code below-----------------------------------------------------------------
121
+
122
+
123
+ if st.sidebar.toggle("Advance LinkedIn Post"):
124
+ url = st.sidebar.text_input("Enter URL", placeholder="Enter URL here...")
125
+ google_api_key=st.sidebar.text_input("Google API Key:",placeholder="Enter Google Search API Key...")
126
+ search_engine_id=st.sidebar.text_input("Search Engine ID:",placeholder="Enter Search Engine ID...")
127
+ google_api_key = "AIzaSyABoOsfUbydc1AfVf2Zjto4MFWNgjLSJmY"
128
+ search_engine_id = "243a392ba3dff442c"
129
+ if st.sidebar.button("Generate Advance Post"):
130
+ if url:
131
+ if api_key:
132
+ if option=="GPT-4":
133
+ model=ChatOpenAI(model="gpt-4-turbo-preview" , temperature=temperature , api_key=api_key)
134
+ elif option=="Cohere":
135
+ model = ChatCohere(cohere_api_key=api_key,temperature=temperature)
136
+ if google_api_key:
137
+ if search_engine_id:
138
+ original_url = get_original_url(url)
139
+ match = re.match(r"https?://(?:www\.)?linkedin\.com/(posts|feed|pulse)/.*", original_url) # checking domain and url page (means it should only be a post nothing else like login page or something else)
140
+
141
+ if match:
142
+ try:
143
+ session_state.advancepost =google_search(url ,model , google_api_key,search_engine_id)
144
+ # session_state.advancepost = advanced_post(all_links ,model ,session_state.paraphrase)
145
+ except (openai.AuthenticationError) as e:
146
+ st.sidebar.error("Enter your valid API key")
147
+ else:
148
+ st.sidebar.error("Put a valid LinkedIn post url only")
149
+ # if len(docs)==0:
150
+ # st.sidebar.error("Please Check your both credentials carefully")
151
+
152
+ else:
153
+ st.sidebar.error("Please enter Search Engine ID")
154
+ else:
155
+ st.sidebar.error("Please enter Google API Key")
156
+ else:
157
+ st.sidebar.error("Please enter API key")
158
+ else:
159
+ st.sidebar.error("Please enter url")
160
+
161
+ advance_post=st.text_area("Advance LinkedIn post",value=session_state.advancepost, height=400)
162
+
163
+
164
+
165
+
166
+ # from streaming_response import StreamHandler
167
+ if st.sidebar.toggle("Message"):
168
+ content=st.sidebar.text_area("Paste your content" ,height=300)
169
+ if st.sidebar.button("Generate Post"):
170
+ if content:
171
+ if api_key:
172
+ # with st.container(height=500):
173
+ # stream_handler = StreamHandler(st.empty())
174
+ # model = ChatCohere(cohere_api_key=api_key,temperature=temperature , streaming=True, callbacks=[stream_handler])
175
+ post_from_content(model ,content)
176
+
177
+
178
  else:
179
+ st.sidebar.error("Please enter API Key")
180
+ else:
181
+ st.sidebar.error("You have not provided any content in Textbox")
182
+
183
 
184
 
185
  # if st.button('Copy Advanced Post'):
 
187
  # st.success('Text copied successfully!')
188
  #--------------------------------------------------------------------------------------------------------------------------------------------------------------
189
 
190
+ # if __name__ == "__main__":
191
+ # main()
192
 
193
 
194
 
blog_post.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.prompts import ChatPromptTemplate
2
+ from langchain_core.output_parsers import StrOutputParser
3
+
4
+
5
+ def post_from_content(model , content):
6
+
7
+
8
+ template=""" As a professional LinkedIn post creator tool, your task is to craft a compelling post based on the content provided. Adhere to the following guidelines:
9
+ 1. Post length should not exceed 3000 characters.
10
+ 2. Select a fitting title, employ professional formatting, incorporate stickers, emojis, relevant hashtags, links (if applicable in the content), and references.
11
+ 3. Additionally, if the content includes code snippets, ensure to present them appropriately within the post.
12
+
13
+ Execute these steps thoughtfully to create an engaging and polished LinkedIn post.
14
+
15
+
16
+
17
+ Content: {content}\n\n
18
+
19
+ Output should only be generated LinkedIn post so that I can quickly copy it and put on my LinkedIn page without doing any modifications.
20
+
21
+ """
22
+
23
+ prompt = ChatPromptTemplate.from_template(template)
24
+ chain = prompt | model | StrOutputParser()
25
+ generated_post=chain.invoke({"content":content})
26
+ return generated_post
paraphrase_post.py CHANGED
@@ -42,58 +42,71 @@ def get_original_url(url):
42
  # Below function extract the post only content from complete web page content and parraphrase the extracted post
43
 
44
  def paraphrased_post(url,model):
45
-
46
  post=scrappost(url)
47
- # print(post)
 
48
 
49
- template=""" You are provided with LinkedIn post below . Paraphrase this post in professional way.You can change the writing style as compared to the provided post .Keep stickers , emojis , links and hastags. Final output should only be paraphrased post .
50
- LinkedIn post: {data}"""
51
 
52
  prompt = ChatPromptTemplate.from_template(template)
53
 
54
  chain = prompt | model | StrOutputParser()
55
  phrased_post=chain.invoke({"data":post})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- data2=extract_data(phrased_post , model)
58
- keywords=data2['Keywords'][:3]
59
- take_aways=data2['Take Aways'][:3]
60
- highlights=data2['Highlights'][:3]
61
- return phrased_post,keywords , take_aways, highlights
62
-
63
 
64
 
65
 
66
 
67
- # Below function extract the details such as keywords , Take aways , highlights and questions
68
- def extract_data(post_data ,model):
69
- keywords = ResponseSchema(name="Keywords",
70
- description="These are the keywords extracted from LinkedIn post",type="list")
71
 
72
- Take_aways = ResponseSchema(name="Take Aways",
73
- description="These are the take aways extracted from LinkedIn post", type= "list")
74
- Highlights=ResponseSchema(name="Highlights",
75
- description="These are the highlights extracted from LinkedIn post", type= "list")
76
 
77
 
78
- response_schema = [
79
- keywords,
80
- Take_aways,
81
- Highlights
82
-
83
- ]
84
- output_parser = StructuredOutputParser.from_response_schemas(response_schema)
85
- format_instructions = output_parser.get_format_instructions()
86
-
87
- template = """
88
- You are a helpful keywords , take aways and highlights extractor from the post of LinkedIn Bot. Your task is to extract relevant keywords , take aways and highlights in descending order of their scores in a list, means high relevant should be on the top .
89
- From the following text message, extract the following information:
90
-
91
- text message: {content}
92
- {format_instructions}
93
- """
94
 
95
- prompt_template = ChatPromptTemplate.from_template(template)
96
- messages = prompt_template.format_messages(content=post_data, format_instructions=format_instructions)
97
- response = model(messages)
98
- output_dict= output_parser.parse(response.content)
99
- return output_dict
 
 
 
 
42
  # Below function extract the post only content from complete web page content and parraphrase the extracted post
43
 
44
  def paraphrased_post(url,model):
 
45
  post=scrappost(url)
46
+ template=""" Create a paraphrased version of a given LinkedIn post while preserving the core message and tone. Ensure the paraphrased content is clear, engaging, and suitable for professional communication on LinkedIn. Focus on rephrasing the post to enhance readability and broaden its appeal to a diverse audience.
47
+ LinkedIn post: {data}
48
 
49
+ The output should only the paraphrased post.
50
+ """
51
 
52
  prompt = ChatPromptTemplate.from_template(template)
53
 
54
  chain = prompt | model | StrOutputParser()
55
  phrased_post=chain.invoke({"data":post})
56
+ return phrased_post
57
+
58
+
59
+
60
+ def generate_details(post_data,model):
61
+ template=""" Extract the top three keywords , take aways and highlights from a LinkedIn post in descending order of relevance. Provide only the three most significant keywords that encapsulate the main topic or message of the post.
62
+ LinkedIn post: {data}
63
+ Keywords:\n\n
64
+
65
+ Output should only include keywords , take aways and highlights.
66
+
67
+ """
68
+ prompt = ChatPromptTemplate.from_template(template)
69
+ chain = prompt | model | StrOutputParser()
70
+ keywords=chain.invoke({"data":post_data})
71
+ return keywords
72
 
 
 
 
 
 
 
73
 
74
 
75
 
76
 
77
+ # # Below function extract the details such as keywords , Take aways , highlights and questions
78
+ # def extract_data(post_data ,model):
79
+ # keywords = ResponseSchema(name="Keywords",
80
+ # description="These are the keywords extracted from LinkedIn post",type="list")
81
 
82
+ # # Take_aways = ResponseSchema(name="Take Aways",
83
+ # # description="These are the take aways extracted from LinkedIn post", type= "list")
84
+ # # Highlights=ResponseSchema(name="Highlights",
85
+ # # description="These are the highlights extracted from LinkedIn post", type= "list")
86
 
87
 
88
+ # response_schema = [
89
+ # keywords,
90
+ # # Take_aways,
91
+ # # Highlights
92
+
93
+ # ]
94
+ # output_parser = StructuredOutputParser.from_response_schemas(response_schema)
95
+ # format_instructions = output_parser.get_format_instructions()
96
+
97
+ # template = """
98
+ # You are a helpful keywords extractor from the post of LinkedIn Bot. Your task is to extract relevant keywords in descending order of their scores in a list, means high relevant should be on the top .
99
+ # From the following text message, extract the following information:
100
+
101
+ # text message: {content}
102
+ # {format_instructions}
103
+ # """
104
 
105
+ # prompt_template = ChatPromptTemplate.from_template(template)
106
+ # messages = prompt_template.format_messages(content=post_data, format_instructions=format_instructions)
107
+ # response = model(messages)
108
+ # output_dict= output_parser.parse(response.content)
109
+ # keywords=output_dict['Keywords'][:3]
110
+ # # take_aways=output_dict['Take Aways'][:3]
111
+ # # highlights=output_dict['Highlights'][:3]
112
+ # return keywords
streaming_response.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.callbacks.base import BaseCallbackHandler
2
+
3
+
4
+ class StreamHandler(BaseCallbackHandler):
5
+ def __init__(self, container, initial_text=""):
6
+ self.container = container
7
+ self.text = initial_text
8
+
9
+ def on_llm_new_token(self, token: str, **kwargs) -> None:
10
+ self.text += token
11
+ self.container.markdown(self.text)
12
+
13
+
14
+ # with st.sidebar:
15
+ # openai_api_key = st.text_input("OpenAI API Key", type="password")
16
+
17
+ # if "messages" not in st.session_state:
18
+ # st.session_state["messages"] = [ChatMessage(role="assistant", content="How can I help you?")]
19
+
20
+ # for msg in st.session_state.messages:
21
+ # st.chat_message(msg.role).write(msg.content)
22
+
23
+ # if prompt := st.chat_input():
24
+ # st.session_state.messages.append(ChatMessage(role="user", content=prompt))
25
+ # st.chat_message("user").write(prompt)
26
+
27
+ # if not openai_api_key:
28
+ # st.info("Please add your OpenAI API key to continue.")
29
+ # st.stop()
30
+
31
+ # with st.chat_message("assistant"):
32
+ # stream_handler = StreamHandler(st.empty())
33
+ # # llm = ChatOpenAI(openai_api_key=openai_api_key, streaming=True, callbacks=[stream_handler])
34
+ # llm = ChatCohere(openai_api_key=openai_api_key, streaming=True, callbacks=[stream_handler])
35
+ # response = llm.invoke(st.session_state.messages)
36
+ # st.session_state.messages.append(ChatMessage(role="assistant", content=response.content))