Abu1998 commited on
Commit
6606435
·
verified ·
1 Parent(s): 88c2fef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -55
app.py CHANGED
@@ -1,78 +1,67 @@
1
- import gradio as gr
2
- from instagrapi import Client
3
- import requests
4
- import tempfile
5
  import os
6
- import pathlib
 
 
 
 
7
 
8
- # ---------- Config ----------
9
- INSTAGRAM_USERNAME = os.getenv("IG_USERNAME") # Hugging Face Secret
10
- INSTAGRAM_PASSWORD = os.getenv("IG_PASSWORD") # Hugging Face Secret
11
- SESSION_FILE = "session.json"
12
 
 
13
  cl = Client()
14
 
 
 
 
 
15
  def login():
16
- """
17
- Login with session file if available, otherwise with username/password.
18
- """
19
  try:
20
- if pathlib.Path(SESSION_FILE).exists():
21
- cl.load_settings(SESSION_FILE)
22
- cl.get_timeline_feed() # test if session works
23
- return "✅ Logged in with saved session"
24
- else:
25
- cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
26
- cl.dump_settings(SESSION_FILE)
27
- return "✅ Logged in with username/password"
28
  except Exception as e:
29
- # If session fails, force new login
30
- try:
31
- cl.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
32
- cl.dump_settings(SESSION_FILE)
33
- return f"⚠️ Session failed, new login: {str(e)}"
34
- except Exception as e2:
35
- return f"❌ Login error: {str(e2)}"
36
 
37
- def upload_post(photo_url: str, caption: str):
38
- """
39
- Downloads photo and uploads to Instagram with caption.
40
- """
 
 
 
 
 
 
41
  try:
42
- # Ensure login
43
  if not cl.user_id:
44
  login()
45
 
46
- # Download photo
 
 
47
  response = requests.get(photo_url, stream=True)
48
  if response.status_code != 200:
49
- return {"status": "error", "message": "Invalid image URL"}
50
 
51
- with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_file:
52
- for chunk in response.iter_content(1024):
53
- tmp_file.write(chunk)
54
- tmp_path = tmp_file.name
55
 
56
- # Upload to Instagram
57
- cl.photo_upload(tmp_path, caption)
 
 
 
58
 
 
 
59
  return {"status": "success", "message": "Photo uploaded successfully!"}
60
 
61
  except Exception as e:
62
  return {"status": "error", "message": str(e)}
63
 
64
- # ---------- Gradio UI ----------
65
- with gr.Blocks() as demo:
66
- gr.Markdown("## 📸 Instagram Auto Uploader (Hugging Face Space)")
67
- with gr.Row():
68
- photo_url = gr.Textbox(label="Photo URL")
69
- caption = gr.Textbox(label="Caption")
70
- output = gr.JSON(label="Result")
71
- upload_btn = gr.Button("Upload to Instagram")
72
-
73
- upload_btn.click(fn=upload_post, inputs=[photo_url, caption], outputs=output)
74
-
75
- # ---------- Launch ----------
76
- if __name__ == "__main__":
77
- login() # auto login on startup
78
- demo.launch()
 
 
 
 
 
1
  import os
2
+ import tempfile
3
+ import requests
4
+ from fastapi import FastAPI, Form
5
+ from instagrapi import Client
6
+ from PIL import Image
7
 
8
+ # Initialize FastAPI app
9
+ app = FastAPI()
 
 
10
 
11
+ # Instagram client
12
  cl = Client()
13
 
14
+ # Load Instagram credentials from HF secrets
15
+ IG_USERNAME = os.getenv("USERNAME")
16
+ IG_PASSWORD = os.getenv("PASSWORD")
17
+
18
  def login():
 
 
 
19
  try:
20
+ cl.login(IG_USERNAME, IG_PASSWORD)
21
+ print("✅ Logged into Instagram")
 
 
 
 
 
 
22
  except Exception as e:
23
+ print(f"⚠️ Login failed: {e}")
24
+ raise
 
 
 
 
 
25
 
26
+ def fix_google_drive_url(url: str) -> str:
27
+ """Convert Google Drive share link to direct-download link"""
28
+ if "drive.google.com" in url:
29
+ if "/d/" in url:
30
+ file_id = url.split("/d/")[1].split("/")[0]
31
+ return f"https://drive.google.com/uc?export=download&id={file_id}"
32
+ return url
33
+
34
+ @app.post("/upload")
35
+ def upload_post(photo_url: str = Form(...), caption: str = Form(...)):
36
  try:
 
37
  if not cl.user_id:
38
  login()
39
 
40
+ # Fix Google Drive links
41
+ photo_url = fix_google_drive_url(photo_url)
42
+
43
  response = requests.get(photo_url, stream=True)
44
  if response.status_code != 200:
45
+ return {"status": "error", "message": f"Invalid image URL: {response.status_code}"}
46
 
47
+ # Save downloaded file
48
+ tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
49
+ tmp_file.write(response.content)
50
+ tmp_file.close()
51
 
52
+ # Validate image
53
+ try:
54
+ Image.open(tmp_file.name).verify()
55
+ except Exception:
56
+ return {"status": "error", "message": "Downloaded file is not a valid image."}
57
 
58
+ # Upload to Instagram
59
+ cl.photo_upload(tmp_file.name, caption)
60
  return {"status": "success", "message": "Photo uploaded successfully!"}
61
 
62
  except Exception as e:
63
  return {"status": "error", "message": str(e)}
64
 
65
+ @app.get("/")
66
+ def root():
67
+ return {"status": "ok", "message": "Instagram uploader is running 🚀"}