Update app.py
Browse files
app.py
CHANGED
|
@@ -1,64 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
def
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
messages.append({"role": "user", "content": val[0]})
|
| 23 |
-
if val[1]:
|
| 24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
| 25 |
|
| 26 |
-
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
max_tokens=max_tokens,
|
| 33 |
-
stream=True,
|
| 34 |
-
temperature=temperature,
|
| 35 |
-
top_p=top_p,
|
| 36 |
-
):
|
| 37 |
-
token = message.choices[0].delta.content
|
| 38 |
-
|
| 39 |
-
response += token
|
| 40 |
-
yield response
|
| 41 |
|
|
|
|
|
|
|
|
|
|
| 42 |
|
|
|
|
| 43 |
"""
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
if __name__ == "__main__":
|
| 64 |
-
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
import gradio as gr
|
| 5 |
+
import requests
|
| 6 |
+
from typing import List, Dict
|
| 7 |
+
from googlesearch import search
|
| 8 |
+
import google.generativeai as genai
|
| 9 |
+
from google.generativeai.types import HarmCategory, HarmBlockThreshold
|
| 10 |
|
| 11 |
+
def initialize_gemini(api_key: str):
|
| 12 |
+
"""Initialize the Google Gemini API with appropriate configurations"""
|
| 13 |
+
genai.configure(api_key=api_key)
|
| 14 |
+
generation_config = {
|
| 15 |
+
"temperature": 0.2,
|
| 16 |
+
"top_p": 0.8,
|
| 17 |
+
"top_k": 40,
|
| 18 |
+
"max_output_tokens": 1024,
|
| 19 |
+
}
|
| 20 |
+
safety_settings = {
|
| 21 |
+
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
|
| 22 |
+
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
|
| 23 |
+
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
|
| 24 |
+
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
model = genai.GenerativeModel(
|
| 28 |
+
model_name="gemini-1.5-flash",
|
| 29 |
+
generation_config=generation_config,
|
| 30 |
+
safety_settings=safety_settings
|
| 31 |
+
)
|
| 32 |
+
return model
|
| 33 |
|
| 34 |
+
def google_search_naics(company_name: str) -> List[str]:
|
| 35 |
+
"""Find potential NAICS codes for a company using Google search"""
|
| 36 |
+
query = f"NAICS code 2022 for {company_name}"
|
| 37 |
+
naics_codes = set()
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
search_results = search(query, stop=5, pause=2)
|
| 41 |
+
|
| 42 |
+
for result_url in search_results:
|
| 43 |
+
try:
|
| 44 |
+
response = requests.get(result_url, timeout=5)
|
| 45 |
+
if response.status_code == 200:
|
| 46 |
+
# Extract 6-digit NAICS codes
|
| 47 |
+
found_codes = re.findall(r'\b\d{6}\b', response.text)
|
| 48 |
+
naics_codes.update(found_codes)
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"Error fetching {result_url}: {e}")
|
| 51 |
+
|
| 52 |
+
return list(naics_codes)[:5] # Return up to 5 extracted NAICS codes
|
| 53 |
+
except Exception as e:
|
| 54 |
+
print(f"Error performing Google search: {str(e)}")
|
| 55 |
+
return []
|
| 56 |
|
| 57 |
+
def get_naics_classification(model, company_name: str, context: str, candidates: List[str]) -> dict:
|
| 58 |
+
"""
|
| 59 |
+
Use Gemini AI to determine the most appropriate NAICS code from candidates
|
| 60 |
+
First provides reasoning, then multiple possibilities with confidence levels
|
| 61 |
+
"""
|
| 62 |
+
try:
|
| 63 |
+
# If we have candidate codes from Google search
|
| 64 |
+
if candidates:
|
| 65 |
+
prompt = f"""
|
| 66 |
+
You are a NAICS code classification expert. Based on the company information provided and the NAICS code candidates found from Google search, determine the most appropriate NAICS code.
|
| 67 |
|
| 68 |
+
Company Name: {company_name}
|
| 69 |
+
Context Information: {context}
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
NAICS Code Candidates from Google Search: {candidates}
|
| 72 |
|
| 73 |
+
First, explain your reasoning for which industry this company belongs to.
|
| 74 |
+
Then list 3 potential NAICS classifications with confidence percentages (must add up to 100%).
|
| 75 |
+
Finally, provide your final conclusion.
|
| 76 |
|
| 77 |
+
Your response should be in this format:
|
| 78 |
+
REASONING: [Your detailed reasoning about the company's industry classification]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
POSSIBILITY_1: [Industry name] - NAICS Code [6-digit code] - [XX]% confidence
|
| 81 |
+
POSSIBILITY_2: [Industry name] - NAICS Code [6-digit code] - [XX]% confidence
|
| 82 |
+
POSSIBILITY_3: [Industry name] - NAICS Code [6-digit code] - [XX]% confidence
|
| 83 |
|
| 84 |
+
CONCLUSION: I am [XX]% confident this company is [industry description] which is NAICS code [6-digit code]
|
| 85 |
"""
|
| 86 |
+
# If no candidates were found from Google search
|
| 87 |
+
else:
|
| 88 |
+
prompt = f"""
|
| 89 |
+
You are a NAICS code classification expert. Based on the company information provided, determine the most appropriate NAICS code.
|
| 90 |
+
|
| 91 |
+
Company Name: {company_name}
|
| 92 |
+
Context Information: {context}
|
| 93 |
+
|
| 94 |
+
First, explain your reasoning for which industry this company belongs to.
|
| 95 |
+
Then list 3 potential NAICS classifications with confidence percentages (must add up to 100%).
|
| 96 |
+
Finally, provide your final conclusion.
|
| 97 |
+
|
| 98 |
+
Your response should be in this format:
|
| 99 |
+
REASONING: [Your detailed reasoning about the company's industry classification]
|
| 100 |
+
|
| 101 |
+
POSSIBILITY_1: [Industry name] - NAICS Code [6-digit code] - [XX]% confidence
|
| 102 |
+
POSSIBILITY_2: [Industry name] - NAICS Code [6-digit code] - [XX]% confidence
|
| 103 |
+
POSSIBILITY_3: [Industry name] - NAICS Code [6-digit code] - [XX]% confidence
|
| 104 |
+
|
| 105 |
+
CONCLUSION: I am [XX]% confident this company is [industry description] which is NAICS code [6-digit code]
|
| 106 |
"""
|
| 107 |
+
response = model.generate_content(prompt)
|
| 108 |
+
response_text = response.text.strip()
|
| 109 |
+
|
| 110 |
+
# Extract reasoning
|
| 111 |
+
reasoning_match = re.search(r'REASONING:(.*?)POSSIBILITY_1:', response_text, re.DOTALL | re.IGNORECASE)
|
| 112 |
+
reasoning = reasoning_match.group(1).strip() if reasoning_match else "No reasoning provided."
|
| 113 |
+
|
| 114 |
+
# Extract possibilities
|
| 115 |
+
possibilities = []
|
| 116 |
+
|
| 117 |
+
# Try to extract possibility 1
|
| 118 |
+
poss1_match = re.search(r'POSSIBILITY_1:(.*?)POSSIBILITY_2:', response_text, re.DOTALL | re.IGNORECASE)
|
| 119 |
+
if poss1_match:
|
| 120 |
+
possibilities.append(poss1_match.group(1).strip())
|
| 121 |
+
|
| 122 |
+
# Try to extract possibility 2
|
| 123 |
+
poss2_match = re.search(r'POSSIBILITY_2:(.*?)POSSIBILITY_3:', response_text, re.DOTALL | re.IGNORECASE)
|
| 124 |
+
if poss2_match:
|
| 125 |
+
possibilities.append(poss2_match.group(1).strip())
|
| 126 |
+
|
| 127 |
+
# Try to extract possibility 3
|
| 128 |
+
poss3_match = re.search(r'POSSIBILITY_3:(.*?)CONCLUSION:', response_text, re.DOTALL | re.IGNORECASE)
|
| 129 |
+
if poss3_match:
|
| 130 |
+
possibilities.append(poss3_match.group(1).strip())
|
| 131 |
+
|
| 132 |
+
# Extract conclusion
|
| 133 |
+
conclusion_match = re.search(r'CONCLUSION:(.*?)
|
| 134 |
+
except Exception as e:
|
| 135 |
+
print(f"Error getting NAICS classification: {str(e)}")
|
| 136 |
+
return {
|
| 137 |
+
"naics_code": "000000",
|
| 138 |
+
"reasoning": f"Error analyzing company: {str(e)}"
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
def find_naics_code(api_key, company_name, company_description):
|
| 142 |
+
"""Main function to find NAICS code that will be called by Gradio"""
|
| 143 |
+
if not api_key or not company_name:
|
| 144 |
+
return "Please provide both API key and company name."
|
| 145 |
+
|
| 146 |
+
try:
|
| 147 |
+
# Initialize Gemini API
|
| 148 |
+
model = initialize_gemini(api_key)
|
| 149 |
+
|
| 150 |
+
# Search for NAICS candidates
|
| 151 |
+
naics_candidates = google_search_naics(company_name)
|
| 152 |
+
|
| 153 |
+
# Get classification
|
| 154 |
+
if not naics_candidates:
|
| 155 |
+
result = get_naics_classification(model, company_name, company_description, [])
|
| 156 |
+
else:
|
| 157 |
+
result = get_naics_classification(model, company_name, company_description, naics_candidates)
|
| 158 |
+
|
| 159 |
+
# Format the output
|
| 160 |
+
output = f"## NAICS Code for {company_name}\n\n"
|
| 161 |
+
output += f"**NAICS Code:** {result['naics_code']}\n\n"
|
| 162 |
+
output += f"**Reasoning:**\n{result['reasoning']}\n\n"
|
| 163 |
+
|
| 164 |
+
# Add possibilities section
|
| 165 |
+
if 'possibilities' in result and result['possibilities']:
|
| 166 |
+
output += f"**Possible Classifications:**\n\n"
|
| 167 |
+
for i, possibility in enumerate(result['possibilities'], 1):
|
| 168 |
+
output += f"{i}. {possibility}\n\n"
|
| 169 |
+
|
| 170 |
+
# Add conclusion
|
| 171 |
+
if 'conclusion' in result and result['conclusion']:
|
| 172 |
+
output += f"**Conclusion:**\n{result['conclusion']}\n\n"
|
| 173 |
+
|
| 174 |
+
if naics_candidates:
|
| 175 |
+
output += f"**Candidate NAICS Codes Found from Google:**\n{', '.join(naics_candidates)}"
|
| 176 |
+
|
| 177 |
+
return output
|
| 178 |
+
|
| 179 |
+
except Exception as e:
|
| 180 |
+
return f"Error: {str(e)}"
|
| 181 |
+
|
| 182 |
+
# Create Gradio Interface
|
| 183 |
+
with gr.Blocks(title="NAICS Code Finder") as app:
|
| 184 |
+
gr.Markdown("# NAICS Code Finder")
|
| 185 |
+
gr.Markdown("This app helps you find the appropriate NAICS code for a company based on its name and description.")
|
| 186 |
+
|
| 187 |
+
with gr.Row():
|
| 188 |
+
with gr.Column():
|
| 189 |
+
api_key = gr.Textbox(label="Google Gemini API Key", placeholder="Enter your Gemini API key here", type="password")
|
| 190 |
+
company_name = gr.Textbox(label="Company Name", placeholder="Enter the company name")
|
| 191 |
+
company_description = gr.Textbox(label="Company Description", placeholder="Enter a brief description of the company", lines=5)
|
| 192 |
+
|
| 193 |
+
submit_btn = gr.Button("Find NAICS Code")
|
| 194 |
+
|
| 195 |
+
with gr.Column():
|
| 196 |
+
output = gr.Markdown(label="Result")
|
| 197 |
+
|
| 198 |
+
submit_btn.click(
|
| 199 |
+
fn=find_naics_code,
|
| 200 |
+
inputs=[api_key, company_name, company_description],
|
| 201 |
+
outputs=output
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
if __name__ == "__main__":
|
| 205 |
+
app.launch()
|
| 206 |
+
, response_text, re.DOTALL | re.IGNORECASE)
|
| 207 |
+
conclusion = conclusion_match.group(1).strip() if conclusion_match else "No conclusion provided."
|
| 208 |
+
|
| 209 |
+
# Extract final NAICS code from conclusion
|
| 210 |
+
naics_match = re.search(r'NAICS code (\d{6})', conclusion)
|
| 211 |
+
if naics_match:
|
| 212 |
+
naics_code = naics_match.group(1)
|
| 213 |
+
else:
|
| 214 |
+
# Try to find any 6-digit code in the conclusion
|
| 215 |
+
code_match = re.search(r'\b(\d{6})\b', conclusion)
|
| 216 |
+
naics_code = code_match.group(1) if code_match else "000000"
|
| 217 |
+
|
| 218 |
+
return {
|
| 219 |
+
"naics_code": naics_code,
|
| 220 |
+
"reasoning": reasoning,
|
| 221 |
+
"possibilities": possibilities,
|
| 222 |
+
"conclusion": conclusion
|
| 223 |
+
}
|
| 224 |
+
except Exception as e:
|
| 225 |
+
print(f"Error getting NAICS classification: {str(e)}")
|
| 226 |
+
return {
|
| 227 |
+
"naics_code": "000000",
|
| 228 |
+
"reasoning": f"Error analyzing company: {str(e)}"
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
def find_naics_code(api_key, company_name, company_description):
|
| 232 |
+
"""Main function to find NAICS code that will be called by Gradio"""
|
| 233 |
+
if not api_key or not company_name:
|
| 234 |
+
return "Please provide both API key and company name."
|
| 235 |
+
|
| 236 |
+
try:
|
| 237 |
+
# Initialize Gemini API
|
| 238 |
+
model = initialize_gemini(api_key)
|
| 239 |
+
|
| 240 |
+
# Search for NAICS candidates
|
| 241 |
+
naics_candidates = google_search_naics(company_name)
|
| 242 |
+
|
| 243 |
+
# Get classification
|
| 244 |
+
if not naics_candidates:
|
| 245 |
+
result = get_naics_classification(model, company_name, company_description, [])
|
| 246 |
+
else:
|
| 247 |
+
result = get_naics_classification(model, company_name, company_description, naics_candidates)
|
| 248 |
+
|
| 249 |
+
# Format the output
|
| 250 |
+
output = f"## NAICS Code for {company_name}\n\n"
|
| 251 |
+
output += f"**NAICS Code:** {result['naics_code']}\n\n"
|
| 252 |
+
output += f"**Reasoning:**\n{result['reasoning']}\n\n"
|
| 253 |
+
|
| 254 |
+
if naics_candidates:
|
| 255 |
+
output += f"**Candidate NAICS Codes Found:**\n{', '.join(naics_candidates)}"
|
| 256 |
+
|
| 257 |
+
return output
|
| 258 |
+
|
| 259 |
+
except Exception as e:
|
| 260 |
+
return f"Error: {str(e)}"
|
| 261 |
|
| 262 |
+
# Create Gradio Interface
|
| 263 |
+
with gr.Blocks(title="NAICS Code Finder") as app:
|
| 264 |
+
gr.Markdown("# NAICS Code Finder")
|
| 265 |
+
gr.Markdown("This app helps you find the appropriate NAICS code for a company based on its name and description.")
|
| 266 |
+
|
| 267 |
+
with gr.Row():
|
| 268 |
+
with gr.Column():
|
| 269 |
+
api_key = gr.Textbox(label="Google Gemini API Key", placeholder="Enter your Gemini API key here", type="password")
|
| 270 |
+
company_name = gr.Textbox(label="Company Name", placeholder="Enter the company name")
|
| 271 |
+
company_description = gr.Textbox(label="Company Description", placeholder="Enter a brief description of the company", lines=5)
|
| 272 |
+
|
| 273 |
+
submit_btn = gr.Button("Find NAICS Code")
|
| 274 |
+
|
| 275 |
+
with gr.Column():
|
| 276 |
+
output = gr.Markdown(label="Result")
|
| 277 |
+
|
| 278 |
+
submit_btn.click(
|
| 279 |
+
fn=find_naics_code,
|
| 280 |
+
inputs=[api_key, company_name, company_description],
|
| 281 |
+
outputs=output
|
| 282 |
+
)
|
| 283 |
|
| 284 |
if __name__ == "__main__":
|
| 285 |
+
app.launch()
|