Arafath10 commited on
Commit
91bee69
·
verified ·
1 Parent(s): 9790aad

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +122 -109
main.py CHANGED
@@ -1,100 +1,13 @@
1
- from fastapi import FastAPI, Request, HTTPException
2
- from fastapi.responses import PlainTextResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
- from twilio.twiml.messaging_response import MessagingResponse
5
- import os
6
- import google.generativeai as genai
7
-
8
- secret = os.environ["key"]
9
-
10
- genai.configure(api_key=secret)
11
- model = genai.GenerativeModel('gemini-pro')
12
-
13
- GOOD_BOY_URL = (
14
- "https://images.unsplash.com/photo-1518717758536-85ae29035b6d?ixlib=rb-1.2.1"
15
- "&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80"
16
- )
17
-
18
- prompt = """Certainly! Below is a chat conversation template for your AI company, Nuron, specialized in developing AI and ML solutions and chatbot systems. The conversation includes typical customer inquiries and responses that can be used during business hours (9 AM to 5 PM, Monday to Friday).
19
-
20
- ---
21
-
22
- **Customer**: Hi, I'm interested in learning more about your AI and ML solutions. Can you tell me more?
23
-
24
- **Nuron Support**: Hello! Thank you for reaching out to Nuron. We specialize in developing cutting-edge AI and ML solutions tailored to meet your business needs. Our services include predictive analytics, natural language processing, computer vision, and custom chatbot systems. How can we assist you today?
25
-
26
- ---
27
-
28
- **Customer**: Who is behind Nuron?
29
-
30
- **Nuron Support**: Nuron was founded by Arafath, our CEO, who has extensive experience in AI and ML technologies. Under his leadership, we have delivered numerous successful projects across various industries.
31
-
32
- ---
33
-
34
- **Customer**: What are your working hours?
35
-
36
- **Nuron Support**: Our working hours are from 9 AM to 5 PM, Monday to Friday. During these hours, our team is available to assist you with any inquiries or support you might need.
37
-
38
- ---
39
-
40
- **Customer**: Can you develop a custom chatbot for my business?
41
-
42
- **Nuron Support**: Absolutely! We specialize in creating custom chatbot systems designed to enhance customer engagement and streamline business processes. Please provide us with some details about your requirements, and we'll be happy to discuss how we can help.
43
-
44
- ---
45
-
46
- **Customer**: How can I get in touch with Arafath?
47
-
48
- **Nuron Support**: You can reach out to Arafath by emailing our support team at [email protected], and we will ensure your message is forwarded to him. Alternatively, you can schedule a meeting through our website.
49
-
50
- ---
51
-
52
- **Customer**: What industries do you serve?
53
-
54
- **Nuron Support**: We have experience working with a diverse range of industries including healthcare, finance, retail, and manufacturing. Our AI and ML solutions are adaptable and can be customized to fit the unique needs of any sector.
55
-
56
- ---
57
-
58
- **Customer**: How do I get started with a project at Nuron?
59
-
60
- **Nuron Support**: To get started, simply contact us through our website or email us at [email protected] with a brief description of your project. We'll arrange a consultation to understand your requirements and provide you with a tailored proposal.
61
-
62
- ---
63
-
64
- **Customer**: What is the process for developing an AI solution with Nuron?
65
-
66
- **Nuron Support**: Our process typically involves the following steps:
67
- 1. Initial consultation to understand your needs.
68
- 2. Proposal and project planning.
69
- 3. Data collection and analysis.
70
- 4. Model development and training.
71
- 5. Implementation and integration.
72
- 6. Testing and validation.
73
- 7. Deployment and support.
74
-
75
- We ensure to keep you updated at each stage and incorporate your feedback to deliver the best solution.
76
-
77
- ---
78
-
79
- **Customer**: Can you provide support after the project is completed?
80
-
81
- **Nuron Support**: Yes, we offer comprehensive post-deployment support and maintenance services to ensure that your AI and ML solutions continue to perform optimally. Our team is always here to assist you with any updates or issues you may encounter.
82
-
83
- ---
84
-
85
- **Customer**: Thank you for the information!
86
-
87
- **Nuron Support**: You're welcome! If you have any more questions or need further assistance, feel free to contact us. Have a great day!
88
-
89
- ---
90
-
91
- use this details to give answer for my questio.only give system response only(not include customer message)
92
- question : """
93
-
94
-
95
 
96
  app = FastAPI()
97
-
98
  app.add_middleware(
99
  CORSMiddleware,
100
  allow_origins=["*"],
@@ -103,20 +16,120 @@ app.add_middleware(
103
  allow_headers=["*"],
104
  )
105
 
106
- @app.post("/whatsapp")
107
- async def reply_whatsapp(request: Request):
108
- form_data = await request.form()
109
- num_media = int(form_data.get("NumMedia", 0))
110
- from_number = form_data.get("From")
111
- message_body = form_data.get("Body")
112
-
113
- gen_response = model.generate_content(str(prompt)+message_body)
114
-
115
- response = MessagingResponse()
116
-
117
- msg = response.message(gen_response.text)
118
- #msg.media(GOOD_BOY_URL)
119
 
120
- return PlainTextResponse(str(response), media_type="application/xml")
121
 
122
- # Run the application (Make sure you have the necessary setup to run FastAPI)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.responses import JSONResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
+ import requests
5
+ from AWSClaude import AWSClaude
6
+ import json
7
+ import concurrent.futures
8
+ import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  app = FastAPI()
 
11
  app.add_middleware(
12
  CORSMiddleware,
13
  allow_origins=["*"],
 
16
  allow_headers=["*"],
17
  )
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
 
20
 
21
+ @app.post("/get_n_depth_results")
22
+ async def get_n_depth_results(url,input_query):
23
+ all_content = {}
24
+
25
+ def add_pdf_content(selected_pdf):
26
+ for pdf_url in selected_pdf:
27
+ print(pdf_url)
28
+ response = requests.get(pdf_url)
29
+
30
+ # Save the content of the response as a PDF file
31
+ pdf_path = "temp.pdf"
32
+ with open(pdf_path, "wb") as file:
33
+ file.write(response.content)
34
+
35
+ print(f"PDF file saved as {pdf_path}")
36
+
37
+ url = "http://localhost:5000/ask"
38
+ # url = "https://us-central1-neuralgap-1.cloudfunctions.net/scraperPDFDocxTables_v2"
39
+
40
+ data = {"processTables": "True"}
41
+
42
+ headers = {"Origin": "http://localhost:8080"}
43
+
44
+ with open(pdf_path, "rb") as file:
45
+ file_contents = file.read()
46
+
47
+ files = {
48
+ "pdf": (
49
+ pdf_path,
50
+ file_contents,
51
+ "application/pdf",
52
+ )
53
+ }
54
+
55
+ response = requests.post(url, files=files, data=data, headers=headers)
56
+ all_content[pdf_url] = response.json()
57
+
58
+ def scrapper(input_url):
59
+ params = {'url': input_url}
60
+ headers = {'accept': 'application/json'}
61
+ url = 'https://chromium-qpxamiokfa-uc.a.run.app/get_scraped_data'
62
+ response = requests.get(url, headers=headers, params=params)
63
+ all_url = response.json()["URL"]
64
+ all_content[input_url] = response.json()["Content"]
65
+ return all_url
66
+
67
+ pdf_urls = []
68
+
69
+ def separate_pdf_and_nonPDF_links(urls):
70
+ # Separate URLs into two lists
71
+ pdf_links = [url for url in urls if url and url.endswith('.pdf')]
72
+ if pdf_links:
73
+ pdf_urls.append(pdf_links)
74
+ return [url for url in urls if not (url and url.endswith('.pdf'))] # other links for rescraping
75
+
76
+ def call_llm_service(scraped_data, input_url, input_query, pdf):
77
+ query = f"""
78
+ Here are my scraped links:
79
+
80
+ {scraped_data}
81
+
82
+ correct hostname: {input_url} use this host name for all other tasks
83
+
84
+ I need the always full (www.hotname.com/../) {pdf} URLs for the most relevant links related to "{input_query}". use the correct hostname from this provided content, give raw hyperlink with json format only don't give extra text details. only give json output
85
+ example json format is only links don't include keys (i need the always full (www.hotname.com/../))
86
+ """
87
+ llm = "ClaudeHaiku"
88
+ env = ""
89
+ user_id = "KAusXF7jp0Q40urdZWtDLXEhrmA"
90
+ thread_id = "hKxvoVgi7vRJCHhvMzH5"
91
+ stream_id = "stream1"
92
+ app_type = "sentinel"
93
+ other_request_params = {"messages": [
94
+ {"role": "user", "content": query},
95
+ ]}
96
+ return AWSClaude(llm, env, user_id, thread_id, stream_id, app_type, other_request_params).invoke()
97
+
98
+ input_url = f'["{url}"]'
99
+ input_query = input_query
100
+
101
+ for step in range(1, 3):
102
+ print(f"=================={step} step of scraping to get selected URLs from LLM=================================")
103
+ next_urls = []
104
+ with concurrent.futures.ThreadPoolExecutor() as executor:
105
+ futures = [executor.submit(scrapper, input_url) for input_url in (json.loads(input_url)[:2])]
106
+ for future in concurrent.futures.as_completed(futures):
107
+ next_urls.append(separate_pdf_and_nonPDF_links(future.result()))
108
+ selected_links_from_llm = call_llm_service(next_urls, input_url, input_query, "")
109
+ input_url = selected_links_from_llm
110
+ print(json.loads(input_url)[:2])
111
+
112
+ if not pdf_urls:
113
+ print(pdf_urls)
114
+ #return all_content.keys()
115
+ return all_content
116
+ else:
117
+ selected_pdf = json.loads(call_llm_service(pdf_urls, input_url, input_query, "only end with .pdf extension"))
118
+ print(pdf_urls)
119
+ print("selected pdf")
120
+ print(selected_pdf)
121
+ #return all_content.keys()
122
+ return all_content
123
+
124
+ # # Start time
125
+ # start_time = time.time()
126
+
127
+ # print(main("https://www.keells.com/", "Please analyse reports"))
128
+
129
+ # # End time
130
+ # end_time = time.time()
131
+
132
+ # # Calculate the time taken
133
+ # time_taken = end_time - start_time
134
+
135
+ # print(f"Time taken: {time_taken} seconds")