SBZ-EDU commited on
Commit
eddaea3
·
0 Parent(s):

Clean deploy

Browse files
Files changed (3) hide show
  1. app.py +58 -0
  2. requirements.txt +13 -0
  3. scraper.py +55 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.llms import HuggingFaceHub
2
+ from langchain_community.embeddings import HuggingFaceEmbeddings
3
+ from langchain_community.vectorstores import FAISS
4
+ from langchain.chains import RetrievalQA
5
+ import os
6
+ import requests
7
+ import gradio as gr
8
+
9
+ # Configuration
10
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
11
+ CLOUDFLARE_API = "https://notary-662-sbz.pages.dev/api/db/chats"
12
+
13
+ # 1. Setup Llama 3 via Hugging Face Inference API
14
+ llm = HuggingFaceHub(
15
+ repo_id="meta-llama/Meta-Llama-3-8B-Instruct",
16
+ huggingfacehub_api_token=HF_TOKEN,
17
+ model_kwargs={"temperature": 0.7, "max_new_tokens": 512}
18
+ )
19
+
20
+ # 2. Setup Persian-capable Embeddings
21
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
22
+
23
+ def query_rag_system(user_query, chat_id="default"):
24
+ # Load the 100 docs index (assuming it's saved locally in the Space)
25
+ try:
26
+ vector_store = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
27
+ qa_chain = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=vector_store.as_retriever())
28
+
29
+ # Get response from Llama 3 + RAG
30
+ result = qa_chain.run(user_query)
31
+
32
+ # 3. Sync with Cloudflare D1
33
+ chat_data = {
34
+ "id": chat_id,
35
+ "title": user_query[:30],
36
+ "docType": "notary_rag_llama",
37
+ "messages": [
38
+ {"role": "user", "text": user_query},
39
+ {"role": "model", "text": result}
40
+ ]
41
+ }
42
+ requests.post(CLOUDFLARE_API, json=chat_data)
43
+
44
+ return result
45
+ except Exception as e:
46
+ return f"خطا در اتصال به بانک اسناد: {str(e)}"
47
+
48
+ # Gradio Interface
49
+ iface = gr.Interface(
50
+ fn=query_rag_system,
51
+ inputs="text",
52
+ outputs="text",
53
+ title="Notary Llama-3 RAG Engine",
54
+ description="این سیستم مستقیماً به Cloudflare و ۱۰۰ فایل PDF محضر متصل است."
55
+ )
56
+
57
+ if __name__ == "__main__":
58
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ langchain
4
+ langchain-community
5
+ langchain-google-genai
6
+ pypdf
7
+ requests
8
+ beautifulsoup4
9
+ fpdf
10
+ huggingface_hub
11
+ google-generativeai
12
+ faiss-cpu
13
+ gradio
scraper.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+ from fpdf import FPDF
4
+ from huggingface_hub import HfApi, upload_file
5
+ import os
6
+
7
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
8
+ DATASET_REPO = "sosa123454321/Notary-PDF-Dataset"
9
+
10
+ def scrape_article_to_pdf(url, output_name):
11
+ print(f"Scraping {url}...")
12
+ try:
13
+ response = requests.get(url)
14
+ soup = BeautifulSoup(response.content, 'html.parser')
15
+
16
+ # Extract main text
17
+ for script in soup(["script", "style"]):
18
+ script.decompose()
19
+
20
+ text = soup.get_text()
21
+ lines = (line.strip() for line in text.splitlines())
22
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
23
+ clean_text = '\n'.join(chunk for chunk in chunks if chunk)
24
+
25
+ # Create PDF
26
+ pdf = FPDF()
27
+ pdf.add_page()
28
+ pdf.set_font("Arial", size=10)
29
+ # Handle non-latin characters by replacing them for the demo
30
+ # For full Persian support, a .ttf font must be loaded using pdf.add_font()
31
+ pdf.multi_cell(0, 10, txt=clean_text.encode('latin-1', 'replace').decode('latin-1'))
32
+
33
+ pdf_path = f"{output_name}.pdf"
34
+ pdf.output(pdf_path)
35
+ print(f"Saved to {pdf_path}")
36
+
37
+ # Upload to HF
38
+ print(f"Uploading to {DATASET_REPO}...")
39
+ upload_file(
40
+ path_or_fileobj=pdf_path,
41
+ path_in_repo=f"documents/{pdf_path}",
42
+ repo_id=DATASET_REPO,
43
+ repo_type="dataset",
44
+ token=HF_TOKEN
45
+ )
46
+ print("Upload successful!")
47
+ return pdf_path
48
+ except Exception as e:
49
+ print(f"Error: {e}")
50
+ return None
51
+
52
+ if __name__ == "__main__":
53
+ # Example usage
54
+ test_url = "https://www.notary662th.ir/induction-manual"
55
+ scrape_article_to_pdf(test_url, "notary_induction_persian")