mgbam commited on
Commit
75cfd1d
·
verified ·
1 Parent(s): 8602110

Update genesis/providers.py

Browse files
Files changed (1) hide show
  1. genesis/providers.py +43 -92
genesis/providers.py CHANGED
@@ -1,114 +1,65 @@
 
 
 
 
 
 
1
  import os
2
  import requests
3
- from typing import List, Dict
4
 
5
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
6
- HF_TOKEN = os.getenv("HF_TOKEN")
7
  GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
 
8
  NCBI_API_KEY = os.getenv("NCBI_API_KEY")
9
  NCBI_EMAIL = os.getenv("NCBI_EMAIL")
10
 
11
- # -------- DeepSeek Summary --------
12
- def run_deepseek_summary(prompt: str) -> str:
13
- """Run a dense scientific summary using DeepSeek API."""
14
- try:
15
- url = "https://api.deepseek.com/v1/chat/completions"
16
- headers = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}
17
- payload = {
18
- "model": "deepseek-science",
19
- "messages": [{"role": "user", "content": prompt}],
20
- "temperature": 0.2
21
- }
22
- r = requests.post(url, headers=headers, json=payload, timeout=60)
23
- r.raise_for_status()
24
- data = r.json()
25
- return data["choices"][0]["message"]["content"]
26
- except Exception as e:
27
- print(f"[DeepSeek] Failed: {e}")
28
- return prompt
29
-
30
- # -------- Gemini Polish --------
31
- def run_gemini_polish(text: str) -> str:
32
- """Polish the summary using Gemini."""
33
- if not GEMINI_API_KEY:
34
- return text
35
  try:
36
- url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={GEMINI_API_KEY}"
37
- payload = {"contents": [{"parts": [{"text": f"Polish and clarify this research report:\n\n{text}"}]}]}
38
- r = requests.post(url, json=payload, timeout=30)
 
 
39
  r.raise_for_status()
40
- data = r.json()
41
- return data["candidates"][0]["content"]["parts"][0]["text"]
42
  except Exception as e:
43
- print(f"[Gemini] Failed: {e}")
44
- return text
45
 
46
- # -------- OpenAI Image --------
47
- def run_openai_image(prompt: str) -> str:
48
- """Generate image using OpenAI API."""
49
- if not OPENAI_API_KEY:
50
- return None
51
  try:
52
- url = "https://api.openai.com/v1/images/generations"
53
- headers = {"Authorization": f"Bearer {OPENAI_API_KEY}"}
54
- payload = {
55
- "model": "gpt-image-1",
56
- "prompt": f"Highly detailed scientific diagram: {prompt}",
57
- "size": "1024x1024"
58
- }
59
- r = requests.post(url, headers=headers, json=payload, timeout=60)
60
  r.raise_for_status()
61
- data = r.json()
62
- return data["data"][0]["url"]
63
  except Exception as e:
64
- print(f"[OpenAI Image] Failed: {e}")
65
- return None
66
 
67
- # -------- Hugging Face Image (Fallback) --------
68
- def run_hf_image(prompt: str) -> str:
69
- """Generate image using Hugging Face Stable Diffusion."""
70
- if not HF_TOKEN:
71
- return None
72
  try:
73
- url = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2"
74
- headers = {"Authorization": f"Bearer {HF_TOKEN}"}
75
- payload = {"inputs": prompt}
76
- r = requests.post(url, headers=headers, json=payload, timeout=60)
 
77
  r.raise_for_status()
78
- # Hugging Face returns raw image bytes, so we save to file
79
- image_path = f"generated_{hash(prompt)}.png"
80
- with open(image_path, "wb") as f:
81
- f.write(r.content)
82
- return image_path
83
  except Exception as e:
84
- print(f"[HF Image] Failed: {e}")
85
- return None
86
 
87
- # -------- PubMed Fallback --------
88
- def pubmed_fallback_search(query: str, api_key: str, email: str) -> List[Dict]:
89
- """Search PubMed if no citations found."""
90
- results = []
91
- if not api_key or not email:
92
- return results
93
  try:
94
- base_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
95
- params = {
96
- "db": "pubmed",
97
- "term": query,
98
- "retmax": 3,
99
- "api_key": api_key,
100
- "email": email,
101
- "retmode": "json"
102
- }
103
- r = requests.get(base_url, params=params, timeout=10)
104
  r.raise_for_status()
105
- ids = r.json().get("esearchresult", {}).get("idlist", [])
106
- for pmid in ids:
107
- results.append({
108
- "type": "PMID",
109
- "id": pmid,
110
- "url": f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/"
111
- })
112
  except Exception as e:
113
- print(f"[PubMed] Failed: {e}")
114
- return results
 
1
+ # genesis/providers.py
2
+ """
3
+ API Providers for GENESIS-AI
4
+ Handles calls to DeepSeek, Gemini, OpenAI, and PubMed.
5
+ """
6
+
7
  import os
8
  import requests
 
9
 
10
+ # ENV
11
+ DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
12
  GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
13
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
14
  NCBI_API_KEY = os.getenv("NCBI_API_KEY")
15
  NCBI_EMAIL = os.getenv("NCBI_EMAIL")
16
 
17
+ def run_deepseek_summary(prompt):
18
+ """Summarize using DeepSeek API."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  try:
20
+ r = requests.post(
21
+ "https://api.deepseek.com/v1/chat/completions",
22
+ headers={"Authorization": f"Bearer {DEEPSEEK_API_KEY}"},
23
+ json={"model": "deepseek-chat", "messages": [{"role": "user", "content": prompt}]}
24
+ )
25
  r.raise_for_status()
26
+ return r.json()["choices"][0]["message"]["content"]
 
27
  except Exception as e:
28
+ return f"[DeepSeek Error] {e}"
 
29
 
30
+ def run_gemini_polish(text):
31
+ """Polish text with Gemini."""
 
 
 
32
  try:
33
+ r = requests.post(
34
+ f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={GEMINI_API_KEY}",
35
+ json={"contents": [{"parts": [{"text": text}]}]}
36
+ )
 
 
 
 
37
  r.raise_for_status()
38
+ return r.json()["candidates"][0]["content"]["parts"][0]["text"]
 
39
  except Exception as e:
40
+ return f"[Gemini Error] {e}"
 
41
 
42
+ def run_openai_image(prompt):
43
+ """Generate image with OpenAI DALL·E or fallback."""
 
 
 
44
  try:
45
+ r = requests.post(
46
+ "https://api.openai.com/v1/images/generations",
47
+ headers={"Authorization": f"Bearer {OPENAI_API_KEY}"},
48
+ json={"model": "gpt-image-1", "prompt": prompt, "size": "1024x1024"}
49
+ )
50
  r.raise_for_status()
51
+ return r.json()["data"][0]["url"]
 
 
 
 
52
  except Exception as e:
53
+ return f"[OpenAI Image Error] {e}"
 
54
 
55
+ def pubmed_fallback_search(query, retmax=5):
56
+ """Simple PubMed search for citations."""
 
 
 
 
57
  try:
58
+ url = f"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
59
+ params = {"db": "pubmed", "term": query, "retmode": "json", "retmax": retmax, "api_key": NCBI_API_KEY}
60
+ r = requests.get(url, params=params)
 
 
 
 
 
 
 
61
  r.raise_for_status()
62
+ ids = r.json()["esearchresult"]["idlist"]
63
+ return [{"pmid": pid, "url": f"https://pubmed.ncbi.nlm.nih.gov/{pid}/"} for pid in ids]
 
 
 
 
 
64
  except Exception as e:
65
+ return [{"error": str(e)}]