pratham0011 commited on
Commit
7f4abc9
·
verified ·
1 Parent(s): 9d6db0a

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +122 -0
  2. firecrawler.py +45 -0
  3. rag.py +61 -0
  4. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import spaces
3
+ import firecrawler
4
+ import rag
5
+ from huggingface_hub import login
6
+ import gradio as gr
7
+ from smolagents import HfApiModel, CodeAgent
8
+
9
+ # login(token = os.getenv('HF_API_KEY'))
10
+ hf_api_key = os.getenv('HF_API_KEY')
11
+
12
+ # Fetch tools
13
+ execute_firecrawl = firecrawler.FireCrawlTool()
14
+ retriever_tool = rag.retriever_tool
15
+
16
+ agent = CodeAgent(
17
+ tools=[execute_firecrawl, retriever_tool],
18
+ model=HfApiModel(token=hf_api_key),
19
+ max_steps=10
20
+ )
21
+
22
+
23
+ def get_answer(url, text):
24
+ """
25
+ A function that takes any question as input and returns the answer using agent.run()
26
+
27
+ Args:
28
+ url (str): The URL to investigate
29
+ text (str): Additional context about the situation
30
+
31
+ Returns:
32
+ str: Detailed analysis report
33
+ """
34
+ # Enhanced prompt with more specific instruction for detailed output
35
+ full_prompt = f'''
36
+ COMPREHENSIVE SCAM DETECTION ANALYSIS
37
+
38
+ Objective: Provide a meticulously detailed, structured assessment of potential online risks.
39
+
40
+ ANALYSIS FRAMEWORK:
41
+ 1. RISK LEVEL
42
+ - Explicitly state an overall risk assessment (Low/Medium/High)
43
+
44
+ 2. URL ANALYSIS
45
+ - Detailed breakdown of URL characteristics
46
+ - Domain reputation assessment
47
+ - Technical red flags
48
+ - Registrar and hosting information insights
49
+
50
+ 3. CONTENT EVALUATION
51
+ - Content quality assessment (use execute_firecrawl to retrieve contents sample)
52
+ - Linguistic and communication pattern analysis
53
+ - Consistency and professionalism evaluation
54
+
55
+ 4. SPECIFIC RED FLAGS
56
+ - List at least 5 concrete indicators of potential scam
57
+ - Use Scamwatch reference material (use retriever_tool)
58
+ - Provide specific evidence for each red flag
59
+ - Categorize red flags (e.g., Technical, Financial, Communication)
60
+
61
+ 5. RECOMMENDED ACTIONS
62
+ - Specific, actionable steps for user protection
63
+ - Use Scamwatch reference material (use retriever_tool)
64
+ - Recommended verification methods
65
+ - Suggested reporting channels
66
+ - Personal safety guidelines
67
+
68
+ 6. ADDITIONAL INSIGHTS
69
+ - Contextual background information
70
+ - Potential motivations behind suspicious activity
71
+ - Broader pattern recognition
72
+
73
+ CONTEXT:
74
+ - URL under investigation: {url}
75
+ - User-provided situation description: {text}
76
+
77
+ CRITICAL INSTRUCTIONS:
78
+ - Maintain objective, evidence-based analysis
79
+ - Talk in terms of risks rather then certainties.
80
+ - Focus on user empowerment and protection
81
+ - Use the retriever_tool tool to look up Scamwatch reference information scam types, reporting scams etc. Where possible prioritise this infomration.
82
+
83
+ '''
84
+
85
+ try:
86
+ answer = agent.run(full_prompt)
87
+ print("Final output:")
88
+ print(answer)
89
+ return answer
90
+ except Exception as e:
91
+ print(f"Error: {str(e)}")
92
+ return f"An error occurred while processing your request: {str(e)}"
93
+
94
+ # Gradio Interface (rest of the code remains the same)
95
+ with gr.Blocks() as demo:
96
+ theme=gr.themes.Monochrome()
97
+
98
+ with gr.Row():
99
+ with gr.Column(scale=1, min_width=300):
100
+ gr.Markdown(
101
+ """
102
+ # ScamShield (agent edition)
103
+ 🛡️ A tool to help users identify scam red flags.
104
+ """)
105
+
106
+ with gr.Row():
107
+ with gr.Column(scale=1, min_width=300):
108
+ input_text = gr.Textbox(label="Description", info="Please describe your concerns regarding the situation", lines=3, value="Is this website a reliable source of investment information?")
109
+ input_url = gr.Textbox(label="URLs", info="Please enter a suspicious URL", lines=3, value="https://fliojinews.xyz/9tKwgmC7")
110
+ btn = gr.Button("Process submission")
111
+
112
+ with gr.Column(scale=2, min_width=300):
113
+ t3 = gr.Textbox(label="Advice", lines=10)
114
+
115
+ btn.click(
116
+ fn=get_answer,
117
+ inputs=[input_url, input_text],
118
+ outputs=[t3]
119
+ )
120
+
121
+ # Launch
122
+ demo.launch()
firecrawler.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from firecrawl import FirecrawlApp
2
+ from pydantic import BaseModel, Field
3
+ from typing import List
4
+ from smolagents import Tool
5
+ import os
6
+
7
+
8
+ #Fetch API key fior firecrawl
9
+ api_key = os.getenv("FIRECRAWL_API_KEY")
10
+
11
+
12
+ class FireCrawlTool(Tool):
13
+ name = "firecrawl_website_qa"
14
+ description = """
15
+ This tool scrapes websites using an API call"""
16
+
17
+ inputs = {
18
+ "website": {
19
+ "type": "string",
20
+ "description": "A singlular website address",
21
+ }
22
+ }
23
+
24
+ output_type = "string"
25
+
26
+
27
+ def forward(self, website: str):
28
+
29
+ # Initialize the FirecrawlApp with the API key
30
+ app = FirecrawlApp(api_key = api_key)
31
+
32
+
33
+ # Scrape a website:
34
+ scrape_result = app.scrape_url(website,
35
+ params={
36
+ 'location': {
37
+ 'country': 'AU'
38
+ }
39
+ }
40
+ )
41
+
42
+ scrape_result = scrape_result['markdown'][:7000]
43
+
44
+
45
+ return scrape_result
rag.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### We first load a knowledge base on which we want to perform RAG
2
+
3
+ import datasets
4
+ from langchain.docstore.document import Document
5
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
6
+ from langchain_community.retrievers import BM25Retriever
7
+ from huggingface_hub import login
8
+ import os
9
+
10
+ knowledge_base = datasets.load_dataset("SuccessfulCrab/web_content", split="train")
11
+
12
+ source_docs = [
13
+ Document(page_content=doc["text"])
14
+ for doc in knowledge_base
15
+ ]
16
+
17
+ text_splitter = RecursiveCharacterTextSplitter(
18
+ chunk_size=500,
19
+ chunk_overlap=50,
20
+ add_start_index=True,
21
+ strip_whitespace=True,
22
+ separators=["\n\n", "\n", ".", " ", ""],
23
+ )
24
+ docs_processed = text_splitter.split_documents(source_docs)
25
+
26
+ ### Since we need to add a vectordb as an attribute of the tool, we cannot simply use the simple tool constructor with a @tool decorator.
27
+ ### Therefore we will follow the advanced setup highlighted in the tools tutorial.
28
+
29
+ from smolagents import Tool
30
+
31
+ class RetrieverTool(Tool):
32
+ name = "retriever"
33
+ description = "Uses semantic search to retrieve the parts of transformers documentation that could be most relevant to answer your query."
34
+ inputs = {
35
+ "query": {
36
+ "type": "string",
37
+ "description": "The query to perform. This should be semantically close to your target documents. Use the affirmative form rather than a question.",
38
+ }
39
+ }
40
+ output_type = "string"
41
+
42
+ def __init__(self, docs, **kwargs):
43
+ super().__init__(**kwargs)
44
+ self.retriever = BM25Retriever.from_documents(
45
+ docs, k=10
46
+ )
47
+
48
+ def forward(self, query: str) -> str:
49
+ assert isinstance(query, str), "Your search query must be a string"
50
+
51
+ docs = self.retriever.invoke(
52
+ query,
53
+ )
54
+ return "\nRetrieved documents:\n" + "".join(
55
+ [
56
+ f"\n\n===== Document {str(i)} =====\n" + doc.page_content
57
+ for i, doc in enumerate(docs)
58
+ ]
59
+ )
60
+
61
+ retriever_tool = RetrieverTool(docs_processed)
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ smolagents
2
+ smolagents[litellm]
3
+ firecrawl-py
4
+ pandas
5
+ langchain
6
+ langchain-community
7
+ sentence-transformers
8
+ rank_bm25
9
+ spaces
10
+ datasets