Spaces:
Sleeping
Sleeping
File size: 4,033 Bytes
a1978fc ecf505f a1978fc ecf505f a1978fc 0faf9b7 ecf505f a5eb7e7 a6c3cb6 ecf505f a6c3cb6 a5eb7e7 ecf505f a5eb7e7 a6c3cb6 a5eb7e7 a1978fc a5eb7e7 a1978fc ecf505f a1978fc ecf505f a6c3cb6 0faf9b7 ecf505f a6c3cb6 ecf505f e367899 7e5b622 0faf9b7 730d34d ecf505f 730d34d a6c3cb6 730d34d ecf505f 730d34d ecf505f a6c3cb6 0ac6a7c a6c3cb6 0ac6a7c a5eb7e7 a6c3cb6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import psycopg2
from psycopg2.extras import RealDictCursor
import os
import google.generativeai as genai
app = FastAPI()
# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Get secrets from Hugging Face Repository Secrets (not .env file)
DATABASE_URL = os.getenv("DATABASE_URL")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
# Configure Gemini if key exists
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
print("β
Gemini configured on cloud")
else:
print("β οΈ No Gemini API key found")
def get_db():
conn = psycopg2.connect(DATABASE_URL, cursor_factory=RealDictCursor)
return conn
def create_table():
conn = get_db()
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS tasks (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL
)
""")
conn.commit()
conn.close()
create_table()
@app.get("/")
def hello():
return {"message": "Hello, Agentic AI! (Cloud with Gemini)"}
@app.post("/tasks")
def create_task(title: str):
conn = get_db()
cursor = conn.cursor()
cursor.execute("INSERT INTO tasks (title) VALUES (%s) RETURNING id", (title,))
task_id = cursor.fetchone()["id"]
conn.commit()
conn.close()
return {"id": task_id, "title": title}
@app.get("/tasks")
def get_tasks():
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT * FROM tasks ORDER BY id DESC")
tasks = cursor.fetchall()
conn.close()
return [{"id": t["id"], "title": t["title"]} for t in tasks]
@app.delete("/tasks/{task_id}")
def delete_task(task_id: int):
conn = get_db()
cursor = conn.cursor()
cursor.execute("DELETE FROM tasks WHERE id = %s", (task_id,))
deleted = cursor.rowcount > 0
conn.commit()
conn.close()
if not deleted:
raise HTTPException(status_code=404, detail="Task not found")
return {"message": "Task deleted"}
# AI endpoint with Gemini
@app.get("/ai-tag")
def ai_tag_paper(title: str, authors: str = ""):
if not GEMINI_API_KEY:
return {"tags": keyword_tag(title), "title": title, "authors": authors}
try:
# This points to a stable, newer model that is currently supported
model = genai.GenerativeModel('gemini-2.5-flash-lite')
prompt = f"""Paper title: "{title}". Authors: "{authors}".
Generate 2-3 relevant tags with emojis. Return ONLY comma-separated tags.
Example: "π€ LLM/AI, π§ Deep Learning"
Tags:"""
response = model.generate_content(prompt)
tags = response.text.strip()
tags = tags.replace("```", "").replace("tags:", "").strip()
if not tags:
tags = keyword_tag(title)
return {"tags": tags, "title": title, "authors": authors}
except Exception as e:
print(f"Gemini error: {e}")
return {"tags": keyword_tag(title), "title": title, "authors": authors}
def keyword_tag(title):
"""Fallback keyword-based tagging"""
title_lower = title.lower()
if any(word in title_lower for word in ['attention', 'transformer', 'llm', 'gpt', 'bert']):
return "π€ LLM/AI, π§ Deep Learning"
elif any(word in title_lower for word in ['big data', 'data processing', 'heterogeneous']):
return "π Big Data, π€ AI-Driven Processing"
elif any(word in title_lower for word in ['solar', 'wind', 'battery', 'energy']):
return "π Energy, βοΈ Renewable"
elif any(word in title_lower for word in ['quantum', 'qubit']):
return "βοΈ Quantum Computing, π¬ Physics"
else:
return "π General Research"
@app.get("/health")
def health():
return {
"status": "ok",
"gemini": "configured" if GEMINI_API_KEY else "missing",
"database": "connected"
} |