Spaces:
Runtime error
Runtime error
sara.mesquita commited on
Commit Β·
9319a7c
1
Parent(s): be251cf
adjusts ia
Browse filesFiles changed (8)
- .idea/material_theme_project_new.xml+3-1
- .idea/misc.xml+4-1
- app.py+246-244
- core/ai.py+83-32
- core/database.py+94-90
- data/viralata.db
- data/viralata.db-journalDeleted
- requirements.txt+1
2 unmodified lines34567892 unmodified lines<component name="MaterialThemeProjectNewConfig"><option name="metadata"><MTProjectMetadataState><option name="userId" value="-47692bf2:19e97ac351f:-7ffd" /></MTProjectMetadataState></option></component>2 unmodified lines345678910112 unmodified lines<component name="MaterialThemeProjectNewConfig"><option name="metadata"><MTProjectMetadataState><option name="migrated" value="true" /><option name="pristineConfig" value="false" /><option name="userId" value="7a3dfa22:19aa6d9c7fa:-7ffd" /></MTProjectMetadataState></option></component>
123456<?xml version="1.0" encoding="UTF-8"?><project version="4"><component name="ProjectRootManager"><output url="file://$PROJECT_DIR$/out" /></component></project>123456789<?xml version="1.0" encoding="UTF-8"?><project version="4"><component name="Black"><option name="sdkName" value="Python 3.11 (novopac-dashboard)" /></component><component name="ProjectRootManager" version="2" languageLevel="JDK_25" project-jdk-name="Python 3.11 (novopac-dashboard)" project-jdk-type="Python SDK"><output url="file://$PROJECT_DIR$/out" /></component></project>
123456734 unmodified lines42434445464748494 unmodified lines5455565758596018 unmodified lines79808182838485868788899091929394952 unmodified lines989910010110210310465 unmodified lines17017117217317417517617717817918018113 unmodified lines1951961971981992002012022032042052062072082092102112122132142152162172182192202212228 unmodified lines23123223323423523623723823924024110 unmodified lines2522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912928 unmodified lines30130230330430530630730830931031131231317 unmodified lines3313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244258 unmodified lines4344354364374384394404414424434445 unmodified lines4504514524534544554564574584594604614624634644654669 unmodified lines4764774784794804814824834844 unmodified lines4894904914924934944954964974984995005015025035045055065075085095105115125135145152 unmodified lines5185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475 unmodified lines5535545555565575585595605615622 unmodified lines56556656756856957057157257357457557657757857910 unmodified lines590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755"""app.py β Spotted AnimalCollaborative mapping of stray animals.Build Small Hackathon Β· Backyard AI Track Β· June 2026"""import jsonimport logging34 unmodified linesC_RED = "#E53935"C_ORANGE = "#FB8C00"# βββ Head HTML para carregar Γcones ββββββββββββββββββββββββββββββββββββββββββ# Esta Γ© a forma correta de injetar bibliotecas externas no GradioHEAD_HTML = """<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" crossorigin="anonymous">"""4 unmodified lines* {{ box-sizing: border-box; font-family: 'Inter', sans-serif; }}/* Mobile-first wrapper */.gradio-container {{max-width: 480px !important;margin: 0 auto !important;18 unmodified linesz-index: 100;box-shadow: 0 2px 8px rgba(0,0,0,.15);}}#top-bar h1 {{margin: 0;font-size: 18px;font-weight: 700;letter-spacing: -0.3px;}}#top-bar small {{font-size: 12px;opacity: .75;font-weight: 400;}}#stats-badge {{background: rgba(255,255,255,.2);border-radius: 20px;2 unmodified linesfont-weight: 600;}}/* Tabs β nav bar look */.tabs > .tab-nav {{background: #fff;border-top: 1px solid #eee;65 unmodified linesbackground: {C_GREEN_L} !important;}}/* =========================================REGISTER TAB & FORM UI========================================= */#register-tab {{padding: 16px 16px 80px;}}.form-card {{background: #ffffff !important;border-radius: 16px !important;13 unmodified linesalign-items: center;gap: 8px;}}.reg-label i {{color: {C_GREEN};font-size: 16px;}}/* ForΓ§ando cores e visual do upload de imagem do Gradio */#photo-upload {{border: 2px dashed #cfcfcf !important;border-radius: 12px !important;background: #f9f9f9 !important;min-height: 180px;}}/* Evitar que os textos fiquem invisΓveis no dark mode */#photo-upload * {{color: #555555 !important;}}#photo-upload:hover {{border-color: {C_GREEN} !important;background: #f4fbf6 !important;}}/* Estilo do Textbox de anotaΓ§Γ΅es */#register-tab textarea {{border-radius: 10px !important;border: 1px solid #e0e0e0 !important;8 unmodified linesbackground: #ffffff !important;box-shadow: 0 0 0 3px {C_GREEN}22 !important;}}#register-tab textarea::placeholder {{color: #a0a0a0 !important;}}/* Submit button dentro do card */#submit-btn {{margin-top: 10px !important;width: 100% !important;10 unmodified lines#submit-btn:hover {{ background: #2d7a4a !important; transform: translateY(-1px); }}#submit-btn:disabled {{ background: #ccc !important; box-shadow: none !important; color: #888 !important; }}/* Status card */#status-card {{margin-top: 16px;border-radius: 12px;font-size: 14px;line-height: 1.5;}}#status-card.ok {{ background: #e8f5e9; color: #2e7d32; border-left: 4px solid {C_GREEN}; padding: 14px 16px; }}#status-card.err {{ background: #ffebee; color: #b71c1c; border-left: 4px solid {C_RED}; padding: 14px 16px; }}/* GPS box */#gps-box {{display: flex;align-items: center;gap: 10px;background: {C_GREEN_L};border-radius: 10px;padding: 12px 14px;font-size: 13px;color: #2e7d32;font-weight: 500;border: 1px solid #c8e6c9;transition: all 0.3s ease;}}#gps-btn {{transition: all 0.2s ease;}}#gps-btn:hover:not(:disabled) {{transform: scale(1.05);box-shadow: 0 2px 8px rgba(56, 140, 89, 0.4);}}#gps-btn:disabled {{opacity: 0.7;cursor: not-allowed;}}/* Animals list */#animals-tab {{ padding: 0 0 80px; background: white; }}8 unmodified linesbox-shadow: 0 2px 8px rgba(0,0,0,.07);border: 1px solid #f0f0f0;}}.animal-avatar {{width: 46px; height: 46px;border-radius: 50%;display: flex; align-items: center; justify-content: center;font-size: 22px;flex-shrink: 0;}}.animal-info {{ flex: 1; min-width: 0; }}.animal-name {{ font-weight: 600; font-size: 14px; color: {C_TEXT}; }}.animal-meta {{ font-size: 12px; color: #888; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}17 unmodified lines}}"""# βββ GPS JavaScript βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# βββ GPS JavaScript βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββGPS_HTML = """<div id="gps-box"><span id="gps-icon" style="font-size:18px"><i class="fa-solid fa-location-crosshairs"></i></span><span id="gps-text">Click the button to detect location</span><button id="gps-btn" style="margin-left:auto;background:#388C59;color:white;border:none;padding:6px 12px;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;"><i class="fa-solid fa-location-dot"></i> Get Location</button></div><script>(function() {var icon = document.getElementById('gps-icon');var text = document.getElementById('gps-text');var btn = document.getElementById('gps-btn');function setCoords(coords) {// Aguarda o Gradio renderizar o textareasetTimeout(function() {var tb = document.querySelector('#gps-coords textarea');if (tb) {var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set;nativeSet.call(tb, JSON.stringify(coords));tb.dispatchEvent(new Event('input', { bubbles: true }));}}, 100);}function requestLocation() {if (!navigator.geolocation) {icon.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i>';text.textContent = 'GPS not available in this browser';btn.style.display = 'none';return;}btn.disabled = true;btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Detecting...';icon.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';text.textContent = 'Waiting for GPS...';navigator.geolocation.getCurrentPosition(function(pos) {var lat = parseFloat(pos.coords.latitude.toFixed(5));var lng = parseFloat(pos.coords.longitude.toFixed(5));icon.innerHTML = '<i class="fa-solid fa-check"></i>';text.innerHTML = '<strong>Location detected:</strong> ' + lat + ', ' + lng;btn.innerHTML = '<i class="fa-solid fa-rotate"></i> Update';btn.disabled = false;btn.style.background = '#2d7a4a';setCoords({ lat: lat, lng: lng });},function(err) {icon.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i>';btn.innerHTML = '<i class="fa-solid fa-location-dot"></i> Try Again';btn.disabled = false;btn.style.background = '#E53935';if (err.code === 1) {text.innerHTML = '<strong>Permission denied.</strong> Enable location in browser settings.';} else if (err.code === 2) {text.innerHTML = '<strong>Location unavailable.</strong> Check if GPS is enabled.';} else if (err.code === 3) {text.innerHTML = '<strong>Timeout.</strong> GPS took too long to respond.';} else {text.textContent = 'Error: ' + err.message;}setCoords({});},{enableHighAccuracy: true,timeout: 15000,maximumAge: 0});}// Evento de clique no botΓ£obtn.addEventListener('click', requestLocation);// Tenta automaticamente apΓ³s 500ms (apΓ³s Gradio carregar)setTimeout(function() {if (navigator.geolocation) {requestLocation();}}, 500);})();</script>"""8 unmodified lines<html><head><meta charset="utf-8"/><link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/><style>body{{margin:0;padding:0;}}#map{{height:100vh;width:100%;}}</style></head><body>5 unmodified linesvar animals = {data_js};if(!animals.length){{var info=L.control({{position:'topright'}});info.onAdd=function(){{var d=L.DomUtil.create('div');d.style='background:white;padding:8px 12px;border-radius:8px;font-size:13px;color:#888;';d.innerHTML='No sightings yet <i class=\"fa-solid fa-paw\"></i>';return d;}};info.addTo(map);}}animals.forEach(function(a){{var color=a.days_since>30?'#E53935':a.count>1?'#FB8C00':'#388C59';var em=a.species==='dog'?'<i class=\"fa-solid fa-dog\"></i>':'<i class=\"fa-solid fa-cat\"></i>';var badge=a.count>1?'<span style="position:absolute;top:-5px;right:-5px;background:white;color:'+color+';border:1.5px solid '+color+';border-radius:10px;min-width:16px;height:16px;font-size:9px;font-weight:700;display:flex;align-items:center;justify-content:center;padding:0 2px;">'+a.count+'</span>':'';var ico=L.divIcon({{html:'<div style="position:relative;background:'+color+';width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:18px;color:white;box-shadow:0 2px 8px rgba(0,0,0,.3);border:2.5px solid white;">'+em+badge+'</div>',className:'',iconSize:[36,36],iconAnchor:[18,18],popupAnchor:[0,-20]}});var sp=a.species==='dog'?'Dog':'Cat';var urg=a.days_since>30?'<br><small style="color:#E53935"><i class=\"fa-solid fa-triangle-exclamation\"></i> Not seen for '+a.days_since+' days</small>':'';L.marker([a.lat,a.lng],{{icon:ico}}).addTo(map).bindPopup('<b>'+em+' '+sp+' #'+a.id+'</b>'+(a.desc?'<br><small>'+a.desc+'</small>':'')+'<br><small><i class=\"fa-solid fa-eye\"></i> '+a.count+'x Β· '+a.last_seen+'</small>'+urg,{{maxWidth:220}});}});</script></body>9 unmodified linesif not animals:return ('<div style="padding:40px 16px;text-align:center;color:#aaa;">''<div style="font-size:48px;margin-bottom:12px;"><i class="fa-solid fa-paw"></i></div>''<div style="font-size:15px;font-weight:500;">No animals registered yet</div>''<div style="font-size:13px;margin-top:6px;">Go to Register and take the first photo!</div>'"</div>")4 unmodified linesexcept Exception:desc = {}is_dog = a["species"] == "dog"em = '<i class="fa-solid fa-dog"></i>' if is_dog else '<i class="fa-solid fa-cat"></i>'sp_pt = "Dog" if is_dog else "Cat"urgent = a.get("days_since", 0) > 30color = C_RED if urgent else C_GREENbadge_cls = "animal-badge urgent" if urgent else "animal-badge"urgent_icon = '<i class="fa-solid fa-triangle-exclamation"></i> ' if urgent else ''breed = desc.get("breed_estimate", "unknown breed")color_coat = desc.get("primary_color", "")meta = f"{breed}{' Β· ' + color_coat if color_coat else ''}"last_seen = a.get("last_seen_short", "")count = a["sighting_count"]cards.append(f"""<div class="animal-card"><div class="animal-avatar" style="background:{color}20; color:{color};">{em}</div><div class="animal-info"><div class="animal-name">{sp_pt} #{a['id']}</div><div class="animal-meta">{meta}</div><div class="animal-meta" style="color:{color};">{urgent_icon}Seen {count}x Β· last: {last_seen}</div></div><div class="{badge_cls}">{count}x</div>2 unmodified linestotal_a = db.total_animals()total_s = db.total_sightings()header = (f'<div class="section-header"><i class="fa-solid fa-paw"></i> {total_a} animals Β· {total_s} sightings</div>')return header + "".join(cards)# βββ Confirmation card HTML βββββββββββββββββββββββββββββββββββββββββββββββββββdef build_confirmation_html(animal_id: int, is_new: bool, count: int, species: str) -> str:em = '<i class="fa-solid fa-dog"></i>' if species == "dog" else '<i class="fa-solid fa-cat"></i>'sp_pt = "dog" if species == "dog" else "cat"if is_new:title = f"New {sp_pt} registered!"sub = "1st sighting β thank you for registering!"else:title = f"{em} Animal recognized!"sub = f"This {sp_pt} has already been spotted <b>{count}x</b> in the region."return f"""<div id="status-card" class="ok"><div style="font-size:24px;margin-bottom:6px;color:{C_GREEN};"><i class="fa-solid fa-check"></i> {em}</div><div style="font-weight:700;font-size:15px;">{title}</div><div>{sub}</div><div style="font-size:12px;margin-top:6px;color:#555;">ID #{animal_id} Β· Sighting saved with location</div></div>"""5 unmodified linesreturn (gr.update(),'<div id="status-card" class="err">''<i class="fa-solid fa-xmark" style="margin-right:6px;"></i> Take a photo of the animal before registering.</div>',)progress(0.15, desc="Analyzing image...")try:coords = json.loads(gps_json) if gps_json and gps_json.strip() else {}except Exception:2 unmodified lineslat = round(float(coords["lat"]), 5) if coords.get("lat") else Nonelng = round(float(coords["lng"]), 5) if coords.get("lng") else Noneprogress(0.40, desc="Identifying animal with AI...")description = ai.analyze_image(image)embedding = ai.get_embedding(description)progress(0.70, desc="Checking previous sightings...")candidates = db.get_all_animals_with_embeddings()match = matcher.find_match(embedding, candidates)photo_path = db.save_photo(image)if match:animal_id, _score = match10 unmodified linesspecies = description.get("species", "dog")is_new = Trueprogress(1.0, desc="Saved!")html = build_confirmation_html(animal_id, is_new, count, species)return gr.update(value=build_map_html()), html# βββ Filter helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef filter_map(species: str, timeframe: str):return gr.update(value=build_map_html(species, timeframe)), species, timeframe# βββ Stats for top bar ββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef get_stats_html():a = db.total_animals()s = db.total_sightings()return f'<div id="stats-badge">{a} animals Β· {s} sightings</div>'# βββ Gradio app βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Blocks(css=CSS, head=HEAD_HTML, theme=gr.themes.Base(), title="Spotted Animal") as demo:# Top bargr.HTML('<div id="top-bar">''<h1><i class="fa-solid fa-paw"></i> Spotted Animal</h1>''<small>Vinhedo, SP</small>'"</div>")species_st = gr.State("all")timeframe_st = gr.State("all")with gr.Tabs(elem_classes="tabs") as tabs:# ββ Tab 1: Map βββββββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Tab("Map"):with gr.Row(elem_classes="filter-row"):btn_all = gr.Button("All", elem_classes="filter-row")btn_dogs = gr.Button("Dogs", elem_classes="filter-row")btn_cats = gr.Button("Cats", elem_classes="filter-row")btn_today = gr.Button("Today", elem_classes="filter-row secondary")btn_week = gr.Button("This week", elem_classes="filter-row secondary")map_html = gr.HTML(build_map_html(), elem_id="map-container")# ββ Tab 2: Register ββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Tab("Register", elem_id="register-tab"):with gr.Column(elem_classes="form-card"):# Step 1: Locationgr.HTML('<div class="reg-label"><i class="fa-solid fa-location-dot"></i> Step 1: Location</div>')gr.HTML(GPS_HTML)# Hidden textbox receives coords from JSgps_coords = gr.Textbox(value="",visible=False,elem_id="gps-coords",interactive=True,)# Step 2: Photogr.HTML('<div class="reg-label"><i class="fa-solid fa-camera"></i> Step 2: Animal Photo</div>')photo_input = gr.Image(label="",type="pil",sources=["upload", "webcam"],interactive=True,show_label=False,elem_id="photo-upload")# Step 3: Notesgr.HTML('<div class="reg-label"><i class="fa-solid fa-file-signature"></i> Step 3: Notes (optional)</div>')notes_input = gr.Textbox(label="",placeholder="E.g.: looks injured, has a collar, has puppies...",lines=2,max_lines=4,show_label=False,)# Submit Buttonsubmit_btn = gr.Button("Register sighting",variant="primary",elem_id="submit-btn",)# Feedback message containerstatus_html = gr.HTML("")# ββ Tab 3: Spotted ββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Tab("Spotted", elem_id="animals-tab"):refresh_btn = gr.Button("Refresh list", size="sm", variant="secondary")animals_display = gr.HTML(build_animals_html())# βββ Events βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Register sightingsubmit_btn.click(process_sighting,inputs=[photo_input, gps_coords, notes_input],outputs=[map_html, status_html],)# Map filters β Allbtn_all.click(lambda: (build_map_html("all", "all"), "all", "all"),outputs=[map_html, species_st, timeframe_st],)# Dogs (keep timeframe)btn_dogs.click(lambda t: (build_map_html("dog", t), "dog", t),inputs=[timeframe_st],outputs=[map_html, species_st, timeframe_st],)# Cats (keep timeframe)btn_cats.click(lambda t: (build_map_html("cat", t), "cat", t),inputs=[timeframe_st],outputs=[map_html, species_st, timeframe_st],)# Today (keep species)btn_today.click(lambda s: (build_map_html(s, "today"), s, "today"),inputs=[species_st],outputs=[map_html, species_st, timeframe_st],)# This week (keep species)btn_week.click(lambda s: (build_map_html(s, "week"), s, "week"),inputs=[species_st],outputs=[map_html, species_st, timeframe_st],)# Refresh spotted listrefresh_btn.click(build_animals_html, outputs=[animals_display])# Reload map when opening appdemo.load(build_map_html, outputs=[map_html])if __name__ == "__main__":# Patch Blocks.get_api_info to prevent crashing with bool schemas.# The bug: gradio_client._json_schema_to_python_type doesn't handle additionalProperties=bool.# This makes the HEAD / route return 500, which prevents launch() from completing.import gradio.blocks as _gb_mod_orig_gai = _gb_mod.Blocks.get_api_infodef _safe_get_api_info(self):try:return _orig_gai(self)except Exception as _e:log.warning(f"get_api_info non-fatal: {_e}")return {}_gb_mod.Blocks.get_api_info = _safe_get_api_infodemo.launch(server_name="0.0.0.0",server_port=int(os.environ.get("PORT", 7860)),show_error=True,show_api=False,)123456734 unmodified lines424344454647484 unmodified lines53545556575818 unmodified lines77787980818283842 unmodified lines8788899091929365 unmodified lines15916016116216316416516613 unmodified lines1801811821831841851861871881891901911921931941951961971981998 unmodified lines20820921021121221321421510 unmodified lines2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552568 unmodified lines26526626726826927027127227327427527627727827928028117 unmodified lines2993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294308 unmodified lines4394404414424434444454464474484494504515 unmodified lines4574584594604614624634644654664674684694704714724734744759 unmodified lines4854864874884894904914924934 unmodified lines4984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305312 unmodified lines5345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665 unmodified lines5725735745755765775785795805812 unmodified lines58458558658758858959059159259359459559659759859910 unmodified lines610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757"""app.py β Animal Visto πΎMapeamento colaborativo de animais de rua.Build Small Hackathon Β· Backyard AI Track Β· Junho 2026"""import jsonimport logging34 unmodified linesC_RED = "#E53935"C_ORANGE = "#FB8C00"# βββ Head HTML ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββHEAD_HTML = """<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" crossorigin="anonymous">"""4 unmodified lines* {{ box-sizing: border-box; font-family: 'Inter', sans-serif; }}.gradio-container {{max-width: 480px !important;margin: 0 auto !important;18 unmodified linesz-index: 100;box-shadow: 0 2px 8px rgba(0,0,0,.15);}}#top-bar h1 {{ margin: 0; font-size: 18px; font-weight: 700; letter-spacing: -0.3px; }}#top-bar small {{ font-size: 12px; opacity: .75; font-weight: 400; }}#stats-badge {{background: rgba(255,255,255,.2);border-radius: 20px;2 unmodified linesfont-weight: 600;}}/* Tabs β nav bar na base */.tabs > .tab-nav {{background: #fff;border-top: 1px solid #eee;65 unmodified linesbackground: {C_GREEN_L} !important;}}/* Register tab */#register-tab {{ padding: 16px 16px 80px; }}.form-card {{background: #ffffff !important;border-radius: 16px !important;13 unmodified linesalign-items: center;gap: 8px;}}.reg-label i {{ color: {C_GREEN}; font-size: 16px; }}#photo-upload {{border: 2px dashed #cfcfcf !important;border-radius: 12px !important;background: #f9f9f9 !important;min-height: 180px;}}#photo-upload * {{ color: #555555 !important; }}#photo-upload:hover {{border-color: {C_GREEN} !important;background: #f4fbf6 !important;}}#register-tab textarea {{border-radius: 10px !important;border: 1px solid #e0e0e0 !important;8 unmodified linesbackground: #ffffff !important;box-shadow: 0 0 0 3px {C_GREEN}22 !important;}}#register-tab textarea::placeholder {{ color: #a0a0a0 !important; }}#submit-btn {{margin-top: 10px !important;width: 100% !important;10 unmodified lines#submit-btn:hover {{ background: #2d7a4a !important; transform: translateY(-1px); }}#submit-btn:disabled {{ background: #ccc !important; box-shadow: none !important; color: #888 !important; }}#status-card {{ margin-top: 16px; border-radius: 12px; font-size: 14px; line-height: 1.5; }}#status-card.ok {{ background: #e8f5e9; color: #2e7d32; border-left: 4px solid {C_GREEN}; padding: 14px 16px; }}#status-card.err {{ background: #ffebee; color: #b71c1c; border-left: 4px solid {C_RED}; padding: 14px 16px; }}#gps-box {{display: flex;align-items: center;gap: 10px;background: {C_GREEN_L};border-radius: 10px;padding: 12px 14px;font-size: 13px;color: #2e7d32;font-weight: 500;border: 1px solid #c8e6c9;}}/* Esconder o campo GPS sem tirar do DOM (para Gradio atualizar o state) */#gps-coords {{display: none !important;height: 0 !important;overflow: hidden !important;margin: 0 !important;padding: 0 !important;}}/* Animals list */#animals-tab {{ padding: 0 0 80px; background: white; }}8 unmodified linesbox-shadow: 0 2px 8px rgba(0,0,0,.07);border: 1px solid #f0f0f0;}}.animal-thumb {{width: 52px; height: 52px;border-radius: 10px;object-fit: cover;flex-shrink: 0;background: #eee;display: flex; align-items: center; justify-content: center;font-size: 24px;overflow: hidden;}}.animal-thumb img {{ width: 100%; height: 100%; object-fit: cover; }}.animal-info {{ flex: 1; min-width: 0; }}.animal-name {{ font-weight: 600; font-size: 14px; color: {C_TEXT}; }}.animal-meta {{ font-size: 12px; color: #888; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}17 unmodified lines}}"""# βββ GPS JavaScript βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββGPS_HTML = """<div id="gps-box"><span id="gps-icon" style="font-size:18px"><i class="fa-solid fa-location-crosshairs"></i></span><span id="gps-text">Clique para detectar localizaΓ§Γ£o</span><button id="gps-btn" style="margin-left:auto;background:#388C59;color:white;border:none;padding:6px 12px;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;"><i class="fa-solid fa-location-dot"></i> Localizar</button></div><script>(function() {// Aguarda o DOM estar completamente pronto antes de inicializarfunction init() {var icon = document.getElementById('gps-icon');var text = document.getElementById('gps-text');var btn = document.getElementById('gps-btn');if (!icon || !text || !btn) { setTimeout(init, 200); return; }// Atualiza o campo oculto do Gradio com as coordenadasfunction setGradioValue(val) {// Tenta encontrar o textarea dentro de #gps-coords (Gradio renderiza visible=True)var attempts = 0;function trySet() {var container = document.getElementById('gps-coords');var tb = container ? (container.querySelector('textarea') || container.querySelector('input')) : null;if (!tb) {// fallback: busca por qualquer textarea com valor de coordstb = document.querySelector('#gps-coords textarea');}if (tb) {// Usa native setter para funcionar com Svelte/Reactvar proto = tb.tagName === 'TEXTAREA'? window.HTMLTextAreaElement.prototype: window.HTMLInputElement.prototype;var nativeSetter = Object.getOwnPropertyDescriptor(proto, 'value').set;nativeSetter.call(tb, val);tb.dispatchEvent(new Event('input', { bubbles: true }));tb.dispatchEvent(new Event('change', { bubbles: true }));} else if (attempts < 10) {attempts++;setTimeout(trySet, 200);}}trySet();}function requestLocation() {if (!navigator.geolocation) {icon.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i>';text.textContent = 'GPS nΓ£o disponΓvel neste navegador';return;}btn.disabled = true;btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Detectando...';icon.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';text.textContent = 'Aguardando GPS...';navigator.geolocation.getCurrentPosition(function(pos) {var lat = parseFloat(pos.coords.latitude.toFixed(5));var lng = parseFloat(pos.coords.longitude.toFixed(5));icon.innerHTML = '<i class="fa-solid fa-check" style="color:#388C59"></i>';text.innerHTML = '<strong>LocalizaΓ§Γ£o detectada:</strong> ' + lat + ', ' + lng;btn.innerHTML = '<i class="fa-solid fa-rotate"></i> Atualizar';btn.disabled = false;btn.style.background = '#2d7a4a';setGradioValue(JSON.stringify({ lat: lat, lng: lng }));},function(err) {icon.innerHTML = '<i class="fa-solid fa-triangle-exclamation" style="color:#E53935"></i>';btn.innerHTML = '<i class="fa-solid fa-location-dot"></i> Tentar novamente';btn.disabled = false;btn.style.background = '#E53935';var msgs = {1: '<strong>PermissΓ£o negada.</strong> Habilite localizaΓ§Γ£o no navegador.',2: '<strong>LocalizaΓ§Γ£o indisponΓvel.</strong> Verifique o GPS.',3: '<strong>Timeout.</strong> GPS demorou demais para responder.',};text.innerHTML = msgs[err.code] || 'Erro: ' + err.message;// Salva coordenadas vazias para nΓ£o bloquear o enviosetGradioValue(JSON.stringify({}));},{ enableHighAccuracy: true, timeout: 15000, maximumAge: 0 });}btn.addEventListener('click', requestLocation);// Tenta automaticamente ao carregar (apΓ³s Gradio inicializar)setTimeout(function() {if (navigator.geolocation) requestLocation();}, 800);}// Inicializa apΓ³s o DOM carregarif (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', init);} else {setTimeout(init, 300);}})();</script>"""# βββ JS para cΓ’mera mobile (capture=environment) βββββββββββββββββββββββββββββCAMERA_JS = """<script>// Adiciona capture=environment ao input de arquivo da foto para abrir cΓ’mera traseira no mobile(function addCameraCapture() {function patch() {var photoUpload = document.getElementById('photo-upload');if (!photoUpload) { setTimeout(patch, 500); return; }var inp = photoUpload.querySelector('input[type=file]');if (inp) {inp.setAttribute('capture', 'environment');inp.setAttribute('accept', 'image/*');} else {setTimeout(patch, 500);}}setTimeout(patch, 1000);})();</script>"""8 unmodified lines<html><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/><style>body{{margin:0;padding:0;}}#map{{height:100vh;width:100%;}}.popup-photo{{width:100%;height:80px;object-fit:cover;border-radius:6px;margin-bottom:6px;}}</style></head><body>5 unmodified linesvar animals = {data_js};if(!animals.length){{var info=L.control({{position:'topright'}});info.onAdd=function(){{var d=L.DomUtil.create('div');d.style='background:white;padding:8px 12px;border-radius:8px;font-size:13px;color:#888;box-shadow:0 2px 8px rgba(0,0,0,.1);';d.innerHTML='Nenhum avistamento ainda <i class="fa-solid fa-paw"></i>';return d;}};info.addTo(map);}}animals.forEach(function(a){{var color=a.days_since>30?'#E53935':a.count>1?'#FB8C00':'#388C59';var em=a.species==='dog'?'π':'π';var badge=a.count>1?'<span style="position:absolute;top:-5px;right:-5px;background:white;color:'+color+';border:1.5px solid '+color+';border-radius:10px;min-width:16px;height:16px;font-size:9px;font-weight:700;display:flex;align-items:center;justify-content:center;padding:0 2px;">'+a.count+'</span>':'';var ico=L.divIcon({{html:'<div style="position:relative;background:'+color+';width:38px;height:38px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:20px;box-shadow:0 2px 8px rgba(0,0,0,.3);border:2.5px solid white;">'+em+badge+'</div>',className:'',iconSize:[38,38],iconAnchor:[19,19],popupAnchor:[0,-22]}});var sp=a.species==='dog'?'CΓ£o':'Gato';var urg=a.days_since>30?'<br><small style="color:#E53935"><i class="fa-solid fa-triangle-exclamation"></i> NΓ£o visto hΓ‘ '+a.days_since+' dias</small>':'';var photoHtml=a.photo_url?'<img src="'+a.photo_url+'" class="popup-photo" onerror="this.style.display=\'none\'"/>':'';var popup='<div style="min-width:180px;">'+photoHtml+'<b>'+sp+' #'+a.id+'</b>'+(a.desc?'<br><small style="color:#555;">'+a.desc+'</small>':'')+'<br><small><i class="fa-solid fa-eye"></i> '+a.count+'x Β· '+a.last_seen+'</small>'+urg+'</div>';L.marker([a.lat,a.lng],{{icon:ico}}).addTo(map).bindPopup(popup,{{maxWidth:220}});}});</script></body>9 unmodified linesif not animals:return ('<div style="padding:40px 16px;text-align:center;color:#aaa;">''<div style="font-size:48px;margin-bottom:12px;">πΎ</div>''<div style="font-size:15px;font-weight:500;">Nenhum animal registrado ainda</div>''<div style="font-size:13px;margin-top:6px;">VΓ‘ para Registrar e tire a primeira foto!</div>'"</div>")4 unmodified linesexcept Exception:desc = {}is_dog = a["species"] == "dog"em = "π" if is_dog else "π"sp_pt = "CΓ£o" if is_dog else "Gato"urgent = a.get("days_since", 0) > 30color = C_RED if urgent else C_GREENbadge_cls = "animal-badge urgent" if urgent else "animal-badge"urgent_icon = '<i class="fa-solid fa-triangle-exclamation"></i> ' if urgent else ''breed = desc.get("breed_estimate", "raΓ§a desconhecida")color_coat = desc.get("primary_color", "")meta = f"{breed}{' Β· ' + color_coat if color_coat else ''}"last_seen = a.get("last_seen_short", "")count = a["sighting_count"]# Foto de thumbnail (usa a mais recente do animal)photo_url = a.get("last_photo_url") or ""if photo_url:thumb_html = f'<img src="{photo_url}" style="width:52px;height:52px;border-radius:10px;object-fit:cover;" onerror="this.parentElement.innerHTML=\'{em}\'">'else:thumb_html = emcards.append(f"""<div class="animal-card"><div class="animal-thumb">{thumb_html}</div><div class="animal-info"><div class="animal-name">{sp_pt} #{a['id']}</div><div class="animal-meta">{meta}</div><div class="animal-meta" style="color:{color};">{urgent_icon}Visto {count}x Β· ΓΊltimo: {last_seen}</div></div><div class="{badge_cls}">{count}x</div>2 unmodified linestotal_a = db.total_animals()total_s = db.total_sightings()header = f'<div class="section-header">πΎ {total_a} animais Β· {total_s} avistamentos</div>'return header + "".join(cards)# βββ Confirmation card HTML βββββββββββββββββββββββββββββββββββββββββββββββββββdef build_confirmation_html(animal_id: int, is_new: bool, count: int, species: str, photo_url: str = "") -> str:em = "π" if species == "dog" else "π"sp_pt = "cΓ£o" if species == "dog" else "gato"if is_new:title = f"Novo {sp_pt} registrado!"sub = "1ΒΊ avistamento β obrigada por registrar!"else:title = f"{em} Animal reconhecido!"sub = f"Este {sp_pt} jΓ‘ foi avistado <b>{count}x</b> na regiΓ£o."photo_html = ""if photo_url:photo_html = f'<img src="{photo_url}" style="width:100%;max-height:160px;object-fit:cover;border-radius:8px;margin-bottom:8px;" onerror="this.style.display=\'none\'">'return f"""<div id="status-card" class="ok">{photo_html}<div style="font-size:24px;margin-bottom:6px;color:{C_GREEN};">β {em}</div><div style="font-weight:700;font-size:15px;">{title}</div><div>{sub}</div><div style="font-size:12px;margin-top:6px;color:#555;">ID #{animal_id} Β· Avistamento salvo com localizaΓ§Γ£o</div></div>"""5 unmodified linesreturn (gr.update(),'<div id="status-card" class="err">''<i class="fa-solid fa-xmark" style="margin-right:6px;"></i> Tire uma foto do animal antes de registrar.</div>',)progress(0.15, desc="Analisando imagem...")try:coords = json.loads(gps_json) if gps_json and gps_json.strip() else {}except Exception:2 unmodified lineslat = round(float(coords["lat"]), 5) if coords.get("lat") else Nonelng = round(float(coords["lng"]), 5) if coords.get("lng") else Noneprogress(0.40, desc="Identificando animal com IA Nemotron...")description = ai.analyze_image(image)embedding = ai.get_embedding(description)progress(0.70, desc="Verificando avistamentos anteriores...")candidates = db.get_all_animals_with_embeddings()match = matcher.find_match(embedding, candidates)photo_path = db.save_photo(image)photo_url = db.photo_url(photo_path) or ""if match:animal_id, _score = match10 unmodified linesspecies = description.get("species", "dog")is_new = Trueprogress(1.0, desc="Salvo!")html = build_confirmation_html(animal_id, is_new, count, species, photo_url)return gr.update(value=build_map_html()), html# βββ Gradio app βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Blocks(css=CSS, head=HEAD_HTML, theme=gr.themes.Base(), title="Animal Visto πΎ") as demo:# Top bargr.HTML('<div id="top-bar">''<h1>πΎ Animal Visto</h1>''<small>Vinhedo, SP</small>'"</div>")species_st = gr.State("all")timeframe_st = gr.State("all")with gr.Tabs(elem_classes="tabs") as tabs:# ββ Tab 1: Mapa ββββββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Tab("πΊοΈ Mapa"):with gr.Row(elem_classes="filter-row"):btn_all = gr.Button("Todos", elem_classes="filter-row")btn_dogs = gr.Button("π CΓ£es", elem_classes="filter-row")btn_cats = gr.Button("π Gatos", elem_classes="filter-row")btn_today = gr.Button("Hoje", elem_classes="filter-row secondary")btn_week = gr.Button("Esta semana", elem_classes="filter-row secondary")map_html = gr.HTML(build_map_html(), elem_id="map-container")# ββ Tab 2: Registrar βββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Tab("π· Registrar", elem_id="register-tab"):with gr.Column(elem_classes="form-card"):# Passo 1: LocalizaΓ§Γ£ogr.HTML('<div class="reg-label"><i class="fa-solid fa-location-dot"></i> Passo 1: LocalizaΓ§Γ£o</div>')gr.HTML(GPS_HTML)# Campo oculto que recebe as coords via JS# Mantemos visible=True mas escondemos via CSS β essencial para Gradio atualizar o stategps_coords = gr.Textbox(value="",elem_id="gps-coords",interactive=True,visible=True,label="gps",)# Passo 2: Fotogr.HTML('<div class="reg-label"><i class="fa-solid fa-camera"></i> Passo 2: Foto do Animal</div>')gr.HTML(CAMERA_JS)photo_input = gr.Image(label="",type="pil",sources=["upload", "webcam"],interactive=True,show_label=False,elem_id="photo-upload",)# Passo 3: ObservaΓ§Γ΅esgr.HTML('<div class="reg-label"><i class="fa-solid fa-file-signature"></i> Passo 3: ObservaΓ§Γ΅es (opcional)</div>')notes_input = gr.Textbox(label="",placeholder="Ex.: parece ferido, tem coleira, tem filhotes...",lines=2,max_lines=4,show_label=False,)submit_btn = gr.Button("Registrar avistamento",variant="primary",elem_id="submit-btn",)status_html = gr.HTML("")# ββ Tab 3: Avistados βββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Tab("πΎ Avistados", elem_id="animals-tab"):refresh_btn = gr.Button("Atualizar lista", size="sm", variant="secondary")animals_display = gr.HTML(build_animals_html())# βββ Eventos ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββsubmit_btn.click(process_sighting,inputs=[photo_input, gps_coords, notes_input],outputs=[map_html, status_html],)btn_all.click(lambda: (build_map_html("all", "all"), "all", "all"),outputs=[map_html, species_st, timeframe_st],)btn_dogs.click(lambda t: (build_map_html("dog", t), "dog", t),inputs=[timeframe_st],outputs=[map_html, species_st, timeframe_st],)btn_cats.click(lambda t: (build_map_html("cat", t), "cat", t),inputs=[timeframe_st],outputs=[map_html, species_st, timeframe_st],)btn_today.click(lambda s: (build_map_html(s, "today"), s, "today"),inputs=[species_st],outputs=[map_html, species_st, timeframe_st],)btn_week.click(lambda s: (build_map_html(s, "week"), s, "week"),inputs=[species_st],outputs=[map_html, species_st, timeframe_st],)refresh_btn.click(build_animals_html, outputs=[animals_display])demo.load(build_map_html, outputs=[map_html])if __name__ == "__main__":import gradio.blocks as _gb_mod_orig_gai = _gb_mod.Blocks.get_api_infodef _safe_get_api_info(self):try:return _orig_gai(self)except Exception as _e:logging.warning(f"get_api_info non-fatal: {_e}")return {}_gb_mod.Blocks.get_api_info = _safe_get_api_info# Serve /data/photos/ para exibir as fotos no appfrom core.database import DATA_DIR, PHOTOS_DIRPHOTOS_DIR.mkdir(parents=True, exist_ok=True)demo.launch(server_name="0.0.0.0",server_port=int(os.environ.get("PORT", 7860)),show_error=True,show_api=False,allowed_paths=[str(DATA_DIR)],)
1234567896 unmodified lines1617181920212212 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001018 unmodified lines110111112113114115116117118119120121122123124125126127128129130131132133"""ai.py β IntegraΓ§Γ£o com HF Inference API + sentence-transformers.VariΓ‘veis de ambiente:HF_TOKEN β token do Hugging Face (obrigatΓ³rio para anΓ‘lise de imagem)HF_MODEL β modelo de visΓ£o a usar (padrΓ£o: meta-llama/Llama-3.2-11B-Vision-Instruct)"""import base64import io6 unmodified lineslog = logging.getLogger(__name__)_DEFAULT_MODEL = "nvidia/Llama-3.2-Nemotron-11B-Vision-Instruct"PROMPT = ("You are analyzing a photo of a stray animal. "12 unmodified linesclass AnimalAI:def __init__(self):token = os.environ.get("HF_TOKEN", "")self.model = os.environ.get("HF_MODEL", _DEFAULT_MODEL)self.client = Noneif token:try:from huggingface_hub import InferenceClientself.client = InferenceClient(model=self.model, token=token)log.info(f"HF InferenceClient initialized: {self.model}")except ImportError:log.warning("huggingface_hub not installed. AI analysis disabled.")else:log.warning("HF_TOKEN not set β AI analysis will use fallback description.")# sentence-transformers para embeddings (gratuito, roda local no Space)self.embedder = Nonetry:from sentence_transformers import SentenceTransformerself.embedder = SentenceTransformer("all-MiniLM-L6-v2")log.info("sentence-transformers loaded: all-MiniLM-L6-v2")except Exception as e:log.warning(f"Could not load sentence-transformers: {e}")# βββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef analyze_image(self, image) -> dict:"""Recebe PIL.Image, retorna dict com descriΓ§Γ£o estruturada do animal.Usa HF Inference API (crΓ©ditos HF). Fallback se token nΓ£o configurado."""if self.client is None:log.info("No HF client β returning fallback description.")return self._fallback()try:img_b64 = self._image_to_b64(image)response = self.client.chat_completion(messages=[{"role": "user","content": [{"type": "image_url","image_url": {"url": f"data:image/jpeg;base64,{img_b64}"},},{"type": "text", "text": PROMPT},],}],max_tokens=300,temperature=0.1,)raw = response.choices[0].message.content or ""return self._parse_json(raw)except Exception as e:log.error(f"HF Inference error: {e}")return self._fallback()def get_embedding(self, description: dict) -> list:"""Gera embedding (384-dim, float32) a partir da descriΓ§Γ£o textual.Roda 100% local com sentence-transformers β sem custo de API."""if self.embedder is None:8 unmodified lines@staticmethoddef _image_to_b64(image) -> str:buf = io.BytesIO()image.thumbnail((800, 800)) # economiza tokens/crΓ©ditosimage.save(buf, format="JPEG", quality=80)return base64.b64encode(buf.getvalue()).decode()@staticmethoddef _parse_json(raw: str) -> dict:match = re.search(r"\{.*\}", raw, re.DOTALL)if match:try:return json.loads(match.group())except json.JSONDecodeError:passreturn AnimalAI._fallback()@staticmethoddef _desc_to_text(d: dict) -> str:parts = [d.get("size", ""), d.get("primary_color", ""), d.get("species", ""), d.get("breed_estimate", "")]marks = d.get("distinctive_marks", [])if marks:parts.append("with " + ", ".join(marks))123456789101112131415166 unmodified lines23242526272829303132333412 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421438 unmodified lines152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184"""ai.py β IntegraΓ§Γ£o com Nemotron 3 Nano Omni via HuggingFace ou NVIDIA NIM.VariΓ‘veis de ambiente (uma das duas Γ© necessΓ‘ria para IA funcionar):HF_TOKEN β token do Hugging Face (usa HF Serverless Inference com crΓ©ditos)NVIDIA_API_KEY β chave NVIDIA NIM (usa integrate.api.nvidia.com β free tier disponΓvel)Modelo: nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16- NEMOTRON 3 NANO OMNI β modelo multimodal (imagem, Γ‘udio, vΓdeo, texto)- 30B parΓ’metros totais, 3B ativos por token (MoE hΓbrido Mamba2-Transformer)- Dentro do limite de 32B do hackathon β- HF: nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16- NVIDIA NIM: nvidia/nemotron-3-nano-omni-30b-a3b"""import base64import io6 unmodified lineslog = logging.getLogger(__name__)# Nemotron 3 Nano Omni β multimodal, 30B total / 3B ativos (MoE)# HF model ID usado pelo InferenceClient_HF_MODEL = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"# NVIDIA NIM model ID (usado se NVIDIA_API_KEY estiver disponΓvel)_NIM_MODEL = "nvidia/nemotron-3-nano-omni-30b-a3b"_DEFAULT_MODEL = _HF_MODELPROMPT = ("You are analyzing a photo of a stray animal. "12 unmodified linesclass AnimalAI:def __init__(self):self.model = os.environ.get("NVIDIA_MODEL", _DEFAULT_MODEL)self.client = Nonehf_token = os.environ.get("HF_TOKEN", "")nvidia_key = os.environ.get("NVIDIA_API_KEY", "")try:from openai import OpenAIif nvidia_key:# NVIDIA NIM β preferencial quando disponΓvel (free tier em build.nvidia.com)self.model = os.environ.get("NVIDIA_MODEL", _NIM_MODEL)self.client = OpenAI(base_url="https://integrate.api.nvidia.com/v1",api_key=nvidia_key,)log.info(f"Nemotron 3 Nano Omni via NVIDIA NIM: {self.model}")elif hf_token:# HuggingFace Inference API β usa crΓ©ditos HFself.model = os.environ.get("NVIDIA_MODEL", _HF_MODEL)self.client = OpenAI(base_url="https://api-inference.huggingface.co/v1/",api_key=hf_token,)log.info(f"Nemotron 3 Nano Omni via HuggingFace: {self.model}")else:log.warning("Sem chave de API β anΓ‘lise de imagem desabilitada.\n""Configure HF_TOKEN no Space (Settings β Secrets).\n""Ou NVIDIA_API_KEY (free em https://build.nvidia.com).")except ImportError:log.warning("openai package nΓ£o instalado. Execute: pip install openai")# sentence-transformers para embeddings locais (sem custo de API)self.embedder = Nonetry:from sentence_transformers import SentenceTransformerself.embedder = SentenceTransformer("all-MiniLM-L6-v2")log.info("sentence-transformers carregado: all-MiniLM-L6-v2")except Exception as e:log.warning(f"NΓ£o foi possΓvel carregar sentence-transformers: {e}")# βββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef analyze_image(self, image) -> dict:"""Recebe PIL.Image, retorna dict com descriΓ§Γ£o estruturada do animal.Usa Nemotron via HF Inference API (ou NVIDIA NIM). Fallback se sem chave."""if self.client is None:log.info("Sem cliente de IA β retornando descriΓ§Γ£o fallback.")return self._fallback()try:img_b64 = self._image_to_b64(image)response = self.client.chat.completions.create(model=self.model,messages=[{"role": "user","content": [{"type": "image_url","image_url": {"url": f"data:image/jpeg;base64,{img_b64}",},},{"type": "text","text": PROMPT,},],}],max_tokens=400,temperature=0.1,)raw = response.choices[0].message.content or ""log.info(f"Nemotron resposta: {raw[:200]}")return self._parse_json(raw)except Exception as e:log.error(f"Erro na API Nemotron: {e}")return self._fallback()def get_embedding(self, description: dict) -> list:"""Gera embedding (384-dim) a partir da descriΓ§Γ£o textual.Roda 100% local com sentence-transformers β sem custo de API."""if self.embedder is None:8 unmodified lines@staticmethoddef _image_to_b64(image) -> str:"""Converte PIL Image para base64 JPEG (max 800px para economizar tokens)."""buf = io.BytesIO()img = image.copy()img.thumbnail((800, 800))img.save(buf, format="JPEG", quality=80)return base64.b64encode(buf.getvalue()).decode()@staticmethoddef _parse_json(raw: str) -> dict:"""Extrai JSON da resposta do modelo (ignora texto ao redor)."""match = re.search(r"\{.*\}", raw, re.DOTALL)if match:try:return json.loads(match.group())except json.JSONDecodeError:passlog.warning("NΓ£o foi possΓvel parsear JSON da resposta β usando fallback")return AnimalAI._fallback()@staticmethoddef _desc_to_text(d: dict) -> str:parts = [d.get("size", ""),d.get("primary_color", ""),d.get("species", ""),d.get("breed_estimate", ""),]marks = d.get("distinctive_marks", [])if marks:parts.append("with " + ", ".join(marks))
123456789101112131415161718197 unmodified lines272829303132333435363738394 unmodified lines444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394953 unmodified lines991001011021031041051061071081091101114 unmodified lines1161171181191201211221239 unmodified lines1331341351361371381395 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671681691701711721734 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002012022031 unmodified line2052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362 unmodified lines239240241"""database.py β SQLite CRUD para animais e avistamentos.Usa /data/ em produΓ§Γ£o (HF Storage Bucket) ou ./data/ localmente."""import jsonimport osimport sqlite3import uuidfrom datetime import datetimefrom pathlib import Pathfrom typing import Optionalimport numpy as npfrom PIL import Image# βββ Paths ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ_hf_data = Path("/data")DATA_DIR = _hf_data if (_hf_data.exists() and os.access(_hf_data, os.W_OK)) else Path("./data")DB_PATH = DATA_DIR / "viralata.db"7 unmodified linesPHOTOS_DIR.mkdir(parents=True, exist_ok=True)self._init_db()# βββ Internal βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _conn(self) -> sqlite3.Connection:conn = sqlite3.connect(str(DB_PATH))conn.row_factory = sqlite3.Rowtry:conn.execute("PRAGMA journal_mode=WAL") # pode falhar em FUSE mountsexcept sqlite3.OperationalError:passconn.execute("PRAGMA foreign_keys=ON")4 unmodified linesif SCHEMA.exists():conn.executescript(SCHEMA.read_text())else:conn.executescript("""CREATE TABLE IF NOT EXISTS animals (id INTEGER PRIMARY KEY AUTOINCREMENT,species TEXT NOT NULL,description TEXT,embedding BLOB,first_seen DATETIME DEFAULT CURRENT_TIMESTAMP,last_seen DATETIME DEFAULT CURRENT_TIMESTAMP,sighting_count INTEGER DEFAULT 1);CREATE TABLE IF NOT EXISTS sightings (id INTEGER PRIMARY KEY AUTOINCREMENT,animal_id INTEGER NOT NULL REFERENCES animals(id),photo_path TEXT,latitude REAL,longitude REAL,notes TEXT,created_at DATETIME DEFAULT CURRENT_TIMESTAMP);""")# βββ Photos βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef save_photo(self, image: Image.Image) -> str:"""Salva PIL Image em /data/photos/, retorna caminho relativo."""filename = f"{uuid.uuid4().hex}.jpg"path = PHOTOS_DIR / filenameimage.save(str(path), format="JPEG", quality=85)return f"photos/{filename}"def photo_url(self, relative_path: Optional[str]) -> Optional[str]:"""Retorna path absoluto para exibiΓ§Γ£o, ou None."""if not relative_path:return Nonefull = DATA_DIR / relative_pathreturn str(full) if full.exists() else None# βββ Animals ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef create_animal(self, description: dict, embedding: list) -> int:"""Cria novo animal, retorna seu id."""emb_blob = np.array(embedding, dtype=np.float32).tobytes()with self._conn() as conn:cur = conn.execute("""INSERT INTO animals (species, description, embedding)VALUES (?, ?, ?)""",(description.get("species", "dog"),json.dumps(description, ensure_ascii=False),3 unmodified linesreturn cur.lastrowiddef update_animal(self, animal_id: int):"""Incrementa sighting_count e atualiza last_seen."""with self._conn() as conn:conn.execute("""UPDATE animalsSET sighting_count = sighting_count + 1,last_seen = CURRENT_TIMESTAMPWHERE id = ?""",(animal_id,),)4 unmodified lines).fetchone()return dict(row) if row else Nonedef get_all_animals_with_embeddings(self) -> list[dict]:"""Retorna todos os animais com embedding desserializado para matching."""with self._conn() as conn:rows = conn.execute("SELECT id, species, description, embedding FROM animals WHERE embedding IS NOT NULL"9 unmodified linesresult.append(d)return result# βββ Sightings ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef add_sighting(self,5 unmodified lines):with self._conn() as conn:conn.execute("""INSERT INTO sightings (animal_id, photo_path, latitude, longitude, notes)VALUES (?, ?, ?, ?, ?)""",(animal_id, photo_path, lat, lng, notes or ""),)def get_animal_sightings(self, animal_id: int) -> list[dict]:with self._conn() as conn:rows = conn.execute("""SELECT * FROM sightings WHERE animal_id = ?ORDER BY created_at DESC""",(animal_id,),).fetchall()return [dict(r) for r in rows]# βββ Map data βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef get_map_data(self, species: str = "all", timeframe: str = "all") -> list[dict]:"""Retorna dados de todos os animais para os pins do mapa.Usa a ΓΊltima localizaΓ§Γ£o conhecida de cada animal."""filters = []params: list = []if species in ("dog", "cat"):filters.append("a.species = ?")4 unmodified linesfilters.append("a.last_seen >= datetime('now', '-7 days')")where = ("WHERE " + " AND ".join(filters)) if filters else ""# Subquery para pegar a ΓΊltima sighting com coordenadassql = f"""SELECTa.id,a.species,a.sighting_count AS count,a.description,strftime('%d/%m/%Y', a.last_seen) AS last_seen,CAST(julianday('now') - julianday(a.last_seen) AS INTEGER) AS days_since,s.latitude AS lat,s.longitude AS lngFROM animals aJOIN sightings s ON s.id = (SELECT id FROM sightingsWHERE animal_id = a.id AND latitude IS NOT NULLORDER BY created_at DESC LIMIT 1){where}ORDER BY a.last_seen DESC"""with self._conn() as conn:rows = conn.execute(sql, params).fetchall()1 unmodified linefor row in rows:d = dict(row)try:desc_obj = json.loads(d["description"] or "{}")d["desc"] = desc_obj.get("description_text") or (f"{desc_obj.get('size','')} {desc_obj.get('primary_color','')} "f"{desc_obj.get('breed_estimate','')}").strip()except Exception:d["desc"] = ""del d["description"]result.append(d)return result# βββ Animals list βββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef get_recent_animals(self, limit: int = 30) -> list[dict]:sql = """SELECTa.*,CAST(julianday('now') - julianday(a.last_seen) AS INTEGER) AS days_since,strftime('%d/%m', a.last_seen) AS last_seen_shortFROM animals aORDER BY a.last_seen DESCLIMIT ?"""with self._conn() as conn:rows = conn.execute(sql, (limit,)).fetchall()return [dict(r) for r in rows]def total_sightings(self) -> int:with self._conn() as conn:2 unmodified linesdef total_animals(self) -> int:with self._conn() as conn:return conn.execute("SELECT COUNT(*) FROM animals").fetchone()[0]1234567891011121314151617187 unmodified lines262728293031323334353637384 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889903 unmodified lines9495969798991001011021034 unmodified lines1081091101111121131149 unmodified lines1241251261271281291305 unmodified lines1361371381391401411421431441451461471481491501511521531541551561571581594 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931 unmodified line1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382 unmodified lines241242243244245"""database.py β SQLite CRUD para animais e avistamentos.Usa /data/ em producao (HF Storage Bucket) ou ./data/ localmente."""import jsonimport osimport sqlite3import uuidfrom pathlib import Pathfrom typing import Optionalimport numpy as npfrom PIL import Image# βββ Paths βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ_hf_data = Path("/data")DATA_DIR = _hf_data if (_hf_data.exists() and os.access(_hf_data, os.W_OK)) else Path("./data")DB_PATH = DATA_DIR / "viralata.db"7 unmodified linesPHOTOS_DIR.mkdir(parents=True, exist_ok=True)self._init_db()# βββ Internal ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _conn(self) -> sqlite3.Connection:conn = sqlite3.connect(str(DB_PATH))conn.row_factory = sqlite3.Rowtry:conn.execute("PRAGMA journal_mode=WAL")except sqlite3.OperationalError:passconn.execute("PRAGMA foreign_keys=ON")4 unmodified linesif SCHEMA.exists():conn.executescript(SCHEMA.read_text())else:conn.executescript("CREATE TABLE IF NOT EXISTS animals ("" id INTEGER PRIMARY KEY AUTOINCREMENT,"" species TEXT NOT NULL,"" description TEXT,"" embedding BLOB,"" first_seen DATETIME DEFAULT CURRENT_TIMESTAMP,"" last_seen DATETIME DEFAULT CURRENT_TIMESTAMP,"" sighting_count INTEGER DEFAULT 1"");""CREATE TABLE IF NOT EXISTS sightings ("" id INTEGER PRIMARY KEY AUTOINCREMENT,"" animal_id INTEGER NOT NULL REFERENCES animals(id),"" photo_path TEXT,"" latitude REAL,"" longitude REAL,"" notes TEXT,"" created_at DATETIME DEFAULT CURRENT_TIMESTAMP"");")# βββ Photos ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef save_photo(self, image: Image.Image) -> str:filename = f"{uuid.uuid4().hex}.jpg"path = PHOTOS_DIR / filenameimage.save(str(path), format="JPEG", quality=85)return f"photos/{filename}"def photo_url(self, relative_path: Optional[str]) -> Optional[str]:if not relative_path:return Nonefull = DATA_DIR / relative_pathreturn str(full) if full.exists() else None# βββ Animals βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef create_animal(self, description: dict, embedding: list) -> int:emb_blob = np.array(embedding, dtype=np.float32).tobytes()with self._conn() as conn:cur = conn.execute("INSERT INTO animals (species, description, embedding) VALUES (?, ?, ?)",(description.get("species", "dog"),json.dumps(description, ensure_ascii=False),3 unmodified linesreturn cur.lastrowiddef update_animal(self, animal_id: int):with self._conn() as conn:conn.execute("UPDATE animals SET sighting_count = sighting_count + 1,"" last_seen = CURRENT_TIMESTAMP WHERE id = ?",(animal_id,),)4 unmodified lines).fetchone()return dict(row) if row else Nonedef get_all_animals_with_embeddings(self) -> list:with self._conn() as conn:rows = conn.execute("SELECT id, species, description, embedding FROM animals WHERE embedding IS NOT NULL"9 unmodified linesresult.append(d)return result# βββ Sightings βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef add_sighting(self,5 unmodified lines):with self._conn() as conn:conn.execute("INSERT INTO sightings (animal_id, photo_path, latitude, longitude, notes)"" VALUES (?, ?, ?, ?, ?)",(animal_id, photo_path, lat, lng, notes or ""),)def get_animal_sightings(self, animal_id: int) -> list:with self._conn() as conn:rows = conn.execute("SELECT * FROM sightings WHERE animal_id = ? ORDER BY created_at DESC",(animal_id,),).fetchall()return [dict(r) for r in rows]# βββ Map data ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef get_map_data(self, species: str = "all", timeframe: str = "all") -> list:filters = []params = []if species in ("dog", "cat"):filters.append("a.species = ?")4 unmodified linesfilters.append("a.last_seen >= datetime('now', '-7 days')")where = ("WHERE " + " AND ".join(filters)) if filters else ""sql = ("SELECT"" a.id,"" a.species,"" a.sighting_count AS count,"" a.description,"" strftime('%d/%m/%Y', a.last_seen) AS last_seen,"" CAST(julianday('now') - julianday(a.last_seen) AS INTEGER) AS days_since,"" s.latitude AS lat,"" s.longitude AS lng,"" (SELECT photo_path FROM sightings"" WHERE animal_id = a.id AND photo_path IS NOT NULL"" ORDER BY created_at DESC LIMIT 1) AS last_photo"" FROM animals a"" JOIN sightings s ON s.id = ("" SELECT id FROM sightings"" WHERE animal_id = a.id AND latitude IS NOT NULL"" ORDER BY created_at DESC LIMIT 1"" )"" " + where +" ORDER BY a.last_seen DESC")with self._conn() as conn:rows = conn.execute(sql, params).fetchall()1 unmodified linefor row in rows:d = dict(row)try:desc_obj = json.loads(d.get("description") or "{}")d["desc"] = desc_obj.get("description_text") or (" ".join(filter(None, [desc_obj.get("size", ""),desc_obj.get("primary_color", ""),desc_obj.get("breed_estimate", ""),]))).strip()except Exception:d["desc"] = ""d.pop("description", None)d["photo_url"] = self.photo_url(d.get("last_photo")) or ""result.append(d)return result# βββ Animals list ββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef get_recent_animals(self, limit: int = 30) -> list:sql = ("SELECT"" a.*,"" CAST(julianday('now') - julianday(a.last_seen) AS INTEGER) AS days_since,"" strftime('%d/%m', a.last_seen) AS last_seen_short,"" (SELECT photo_path FROM sightings"" WHERE animal_id = a.id AND photo_path IS NOT NULL"" ORDER BY created_at DESC LIMIT 1) AS last_photo_path"" FROM animals a"" ORDER BY a.last_seen DESC"" LIMIT ?")with self._conn() as conn:rows = conn.execute(sql, (limit,)).fetchall()result = []for row in rows:d = dict(row)d["last_photo_url"] = self.photo_url(d.get("last_photo_path")) or ""result.append(d)return resultdef total_sightings(self) -> int:with self._conn() as conn:2 unmodified linesdef total_animals(self) -> int:with self._conn() as conn:return conn.execute("SELECT COUNT(*) FROM animals").fetchone()[0]as conn:return conn.execute("SELECT COUNT(*) FROM animals").fetchone()[0]
4 unmodified lines5674 unmodified linespillow>=10.0.0sentence-transformers>=2.7.0numpy>=1.26.04 unmodified lines56784 unmodified linespillow>=10.0.0sentence-transformers>=2.7.0numpy>=1.26.0openai>=1.0.0
.idea/material_theme_project_new.xml+3-1
.idea/misc.xml+4-1
app.py+246-244
core/ai.py+83-32
core/database.py+94-90
data/viralata.db
data/viralata.db-journalDeleted
requirements.txt+1