minzo456 commited on
Commit
1cd88ce
·
verified ·
1 Parent(s): 6767b71

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -28
app.py CHANGED
@@ -1,34 +1,54 @@
1
  from fastapi import FastAPI, Request
2
  from transformers import pipeline
3
  import torch
4
- from ddgs import DDGS
 
 
 
 
5
  from fastapi.middleware.cors import CORSMiddleware
6
  import uvicorn
7
 
8
  app = FastAPI()
 
9
 
10
- app.add_middleware(
11
- CORSMiddleware,
12
- allow_origins=["*"],
13
- allow_methods=["*"],
14
- allow_headers=["*"],
15
- )
16
-
17
- # 🔱 Loading local engine (SmolLM2 - Stable Version)
18
- print("🔱 Initializing Internal Neural Core...")
19
- pipe = pipeline(
20
- "text-generation",
21
- model="HuggingFaceTB/SmolLM2-1.7B-Instruct",
22
- device_map="auto",
23
- torch_dtype=torch.bfloat16 # RAM එක ඉති කර ගැනීම
24
- )
25
- print("🔱 Engine Ready!")
26
-
27
- def web_search(query):
 
 
 
 
 
 
 
 
 
 
28
  try:
29
- with DDGS() as ddgs:
30
- results = [r for r in ddgs.text(query, max_results=2)]
31
- return " ".join([r['body'] for r in results])
 
 
 
 
 
32
  except: return ""
33
 
34
  @app.post("/generate")
@@ -36,19 +56,24 @@ async def generate(request: Request):
36
  try:
37
  data = await request.json()
38
  user_prompt = data.get("prompt")
39
- context = web_search(user_prompt)
40
 
 
 
 
 
 
 
 
 
 
41
  messages = [
42
- {"role": "system", "content": f"You are Elephant AI Pro by MINZO-PRIME. Web Data: {context}"},
43
  {"role": "user", "content": user_prompt},
44
  ]
45
 
46
  prompt = pipe.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
47
  outputs = pipe(prompt, max_new_tokens=500, do_sample=True, temperature=0.7)
48
-
49
- # පිළිතුර පමණක් වෙන් කර ගැනීම
50
- generated_text = outputs[0]["generated_text"]
51
- response = generated_text.split("<|im_start|>assistant")[-1].strip()
52
 
53
  return {"response": response}
54
 
 
1
  from fastapi import FastAPI, Request
2
  from transformers import pipeline
3
  import torch
4
+ import requests
5
+ import re
6
+ import urllib.parse
7
+ from bs4 import BeautifulSoup
8
+ import feedparser
9
  from fastapi.middleware.cors import CORSMiddleware
10
  import uvicorn
11
 
12
  app = FastAPI()
13
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
14
 
15
+ # 🔱 Engine Initialization
16
+ print("🔱 Initializing Neural Core with Advanced Search...")
17
+ pipe = pipeline("text-generation", model="HuggingFaceTB/SmolLM2-1.7B-Instruct", device_map="auto", torch_dtype=torch.bfloat16)
18
+
19
+ # 🔱 WormGPT logic එකෙන් ගත් RSS Feeds
20
+ RSS_FEEDS = {
21
+ 'exploits': ['https://www.exploit-db.com/rss.xml', 'https://cve.circl.lu/last/rss.xml'],
22
+ 'hacking': ['https://feeds.feedburner.com/TheHackersNews', 'https://www.darkreading.com/rss.xml'],
23
+ 'sri_lanka': ['https://www.adaderana.lk/rss.php'],
24
+ 'tech': ['https://feeds.bbci.co.uk/news/technology/rss.xml']
25
+ }
26
+
27
+ def fetch_rss_logic(query):
28
+ """ප්‍රශ්නය අනුව අදාළ RSS Feed එක ීක්ෂාරීම"""
29
+ category = 'tech'
30
+ if any(w in query.lower() for w in ['exploit', 'cve', 'hack']): category = 'exploits'
31
+ elif any(w in query.lower() for w in ['lanka', 'colombo']): category = 'sri_lanka'
32
+
33
+ for url in RSS_FEEDS.get(category, RSS_FEEDS['tech']):
34
+ try:
35
+ feed = feedparser.parse(url)
36
+ if feed.entries:
37
+ return "\n".join([f"News: {e.title} - {e.summary[:200]}" for e in feed.entries[:3]])
38
+ except: continue
39
+ return ""
40
+
41
+ def duckduckgo_search(query):
42
+ """DuckDuckGo හරහා Web තොරතුරු සෙවීම"""
43
  try:
44
+ url = f"https://html.duckduckgo.com/html/?q={urllib.parse.quote(query)}"
45
+ headers = {'User-Agent': 'Mozilla/5.0'}
46
+ r = requests.get(url, headers=headers, timeout=10)
47
+ soup = BeautifulSoup(r.text, 'html.parser')
48
+ results = []
49
+ for a in soup.find_all('a', class_='result__a', limit=3):
50
+ results.append(a.get_text())
51
+ return "\n".join(results)
52
  except: return ""
53
 
54
  @app.post("/generate")
 
56
  try:
57
  data = await request.json()
58
  user_prompt = data.get("prompt")
 
59
 
60
+ # 🔱 Web Search Logic Execution
61
+ search_info = ""
62
+ if any(k in user_prompt.lower() for k in ['news', 'latest', 'today', 'hack', 'cve']):
63
+ search_info = fetch_rss_logic(user_prompt)
64
+
65
+ if not search_info:
66
+ search_info = duckduckgo_search(user_prompt)
67
+
68
+ # 🔱 Neural Response Generation
69
  messages = [
70
+ {"role": "system", "content": f"You are Elephant AI Pro by MINZO-PRIME. Live Data: {search_info}"},
71
  {"role": "user", "content": user_prompt},
72
  ]
73
 
74
  prompt = pipe.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
75
  outputs = pipe(prompt, max_new_tokens=500, do_sample=True, temperature=0.7)
76
+ response = outputs[0]["generated_text"].split("<|im_start|>assistant")[-1].strip()
 
 
 
77
 
78
  return {"response": response}
79